根據兩種不同遍歷結果重構二叉樹


leetcode原題:題目1 題目2
這里假設給的遍歷都有中序遍歷,我們先根據先序遍歷或后序遍歷找到根結點的值,然后據此可判斷,在中序遍歷的結果向量中,在根節點之前的部分數組組成它的左子樹,根節點之后組成它的右子數。采用深度遞歸dfs。

題1:已知中序和后序遍歷結果

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
class Solution {
    TreeNode* dfs(int post, int instart, int inend,vector<int>& inorder, vector<int>& postorder)
    {
        if(post<0||instart>inend)
        return NULL;
        TreeNode* root=new TreeNode(postorder[post]);
        int index=0;
        for(int i=instart;i<=inend;i++)
        if(inorder[i]==postorder[post])
        {
            index=i;
            break;
        }
        TreeNode* left=dfs(post-(inend-index)-1,instart,index-1,inorder,postorder);
        TreeNode* right=dfs(post-1,index+1,inend,inorder,postorder);
        root->left=left;
        root->right=right;
        return root;
    }
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int n=postorder.size();
        return dfs(n-1,0,n-1,inorder,postorder);
    }
};

題2:已知中序和前序遍歷結果

/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */
class Solution {
    TreeNode * dfs(int preStart, int inStart, int inEnd, vector<int>& preorder, vector<int>& inorder)
    {
        if(preStart>preorder.size()-1||inStart>inEnd)
        return NULL;
        TreeNode* root=new TreeNode(preorder[preStart]);
        int index=0;
        for(int i=inStart;i<=inEnd;i++)
        if(inorder[i]==preorder[preStart])
          { index=i;break;}
        TreeNode* left=dfs(preStart+1,inStart,index-1,preorder,inorder);
        TreeNode* right=dfs(preStart+index-inStart+1,index+1,inEnd,preorder,inorder);
        root->left=left;
        root->right=right;
        return root;
    }
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
       return dfs(0,0,inorder.size()-1,preorder,inorder); 
    }
};

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com