Wednesday, November 6, 2013

106. Construct Binary Tree from Inorder and Postorder Traversal ---M

Given inorder and postorder traversal of a tree, construct the binary tree.

Note:
You may assume that duplicates do not exist in the tree.

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

A:
思路和上一题一样。 只不过在确定局部root的时候,是取的postorder最后的一个点
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        int n = inorder.size();
        return helper(inorder, 0, n-1, postorder, 0,n-1);
    }
private:
    TreeNode* helper(vector<int> & inorder, int iBegin,int iEnd, vector<int> & postorder, int pBegin, int pEnd){
        if(iBegin > iEnd){
            return nullptr;
        }
        TreeNode * pRoot = new TreeNode(postorder[pEnd]);
        int iRoot = iBegin;
        for(;iRoot<=iEnd;iRoot++){
            if(inorder[iRoot] == pRoot->val){
                break;
            }
        }
        pRoot->left = helper(inorder, iBegin,iRoot-1,postorder,pBegin, pBegin+iRoot-1-iBegin);
        pRoot->right = helper(inorder, iRoot+1, iEnd, postorder, pBegin+iRoot-iBegin,pEnd-1);
        return pRoot;
    }
};



No comments:

Post a Comment