Wednesday, November 6, 2013

Construct Binary Tree from Preorder and Inorder Traversal

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

A:
就是先通过preorder中的第一个,找到root。  然后,在inorder中找到 其对应的position,  position 左边的就是左子树,  右边的就是右子树。   (相应的范围在preorder中,只需要计算左子树节点的数目,就可以确定。)

/**
 * 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 {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int n = preorder.size();
        return helper(preorder, 0, n, inorder, 0, n); //left close, right open
    }
private:
    TreeNode* helper(vector<int>& preorder, int pa, int pb, vector<int>& inorder, int ia,int ib) {
        if(pa>=pb)
            return NULL;
        TreeNode * root = new TreeNode(preorder[pa]);
        int ix = ia;
        for(; ix< ib;++ix) // find root->val in inorder
            if(inorder[ix] == root->val)
                break;
        int nLeft = ix-ia; // number of node in left child 
        root->left = helper(preorder, pa+1, pa+1+nLeft, inorder, ia, ix);
        root->right = helper(preorder,pa+1+nLeft, pb, inorder, ix+1, ib);
        return root;
    }
};

犯的错误是:  当nLeftChild的定义搞错了,加了个1.
在计算root.left 和 root.right 的inorder指针的时候,就忘了一个是要-1 , 一个是要+1.  (刚开始,自己是一个没有改,一个+2了)




Mistakes:
1:  主要就是,递归调用的时候, preOrder的low,high参数,要好好考虑。 (尤其是, preorder时, 不需要跳过一个数字的。)



No comments:

Post a Comment