LeetCode题目:Construct Binary Tree from Inorder and Postorder Traversal

By | 2012 年 12 月 12 日

这题和上一道题类似,也是首先在postorder中,最后那一个肯定是整棵树的根,然后在inorder中查找这个根,找到之后就能确定左子树和右子树的后序遍历和中序遍历,然后递归求解。



Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.



代码:120ms过大集合

/**
 * 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 &iorder, int isi, int iei, vector &porder, int psi, int pei) {
        if(iei - isi < 0 || iei - isi != pei - psi) {
            return NULL;
        }
        //the porder[pei] is the root of this tree
        TreeNode *root = new TreeNode(porder[pei]);
        //find the root in the iorder to seperate it into left sub tree and right sub tree
        int riii = -1;//root index in inorder array
        for(int i = isi; i <= iei; ++i) {
            if(iorder[i] == root->val) {
                riii = i;
                break;
            }
        }
        if(riii == -1) return root;//error
        int lnodes = riii - isi;
        //for the left sub tree
        //the isi to riii - 1 in inorder array will be it's inorder traversal
        //and the psi to psi + lnodes - 1 in postorder array will be it's post order traversal
        root->left = buildTree(iorder, isi, riii - 1, porder, psi, psi + lnodes - 1);
        //for the right sub tree is similary to the left
        root->right = buildTree(iorder, riii + 1, iei, porder, psi + lnodes, pei - 1);
        return root;
    }
    TreeNode *buildTree(vector &inorder, vector &postorder) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        return buildTree(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() -1);
    }
};

4 thoughts on “LeetCode题目:Construct Binary Tree from Inorder and Postorder Traversal

发表评论

电子邮件地址不会被公开。 必填项已用*标注