已知二叉树的中序遍历和后续遍历,进行重建二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wyn126/article/details/81865949

题目:
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
     return solve(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
    }
     TreeNode*  solve(vector<int> &inorder,int beg1,int end1,vector<int> &postorder,int beg2,int end2)
    {
        if(beg1>end1)
            return NULL;
        TreeNode *root=new TreeNode(postorder[end2]);
        int count=0;
        int i=beg1;
        for(;i<=end1&&inorder[i]!=postorder[end2];i++)
            count++;
        root->left=solve(inorder,beg1,i-1,postorder,beg2,beg2+count-1);
        root->right=solve(inorder,i+1,end1,postorder,beg2+count,end2-1);

        return root;
    }

};

猜你喜欢

转载自blog.csdn.net/wyn126/article/details/81865949