Construct Binary Tree from Preorder and Inorder Traversal

Description:

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

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

Code:

TreeNode * buildTree(vector<int>& preorder, int preBegin, int preEnd, vector<int>& inorder, int inBegin, int inEnd)
 {
    TreeNode*root =NULL;

    if (preEnd >= preBegin)
    {
        root = new TreeNode(preorder[preBegin]);
        int n = inEnd-inBegin+1;
        int rootIndex = 0;
        for (int i = inBegin; i <= inEnd; ++i)
        {
            if (inorder[i] == preorder[preBegin])
            {
                rootIndex = i;
                break;
            }
        }
        
        if (rootIndex!=inBegin)
        {
            root->left = buildTree(preorder, preBegin+1, preBegin+(rootIndex-inBegin), inorder, inBegin, rootIndex-1);
        }
        if (rootIndex!=inEnd)
        {
            root->right = buildTree(preorder, preBegin+1+(rootIndex-inBegin), preEnd, inorder, rootIndex+1, inEnd);
        }
    }
    return root;  
 }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return buildTree(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1);
    }

 

posted @ 2015-06-20 15:19  Rosanne  阅读(177)  评论(0编辑  收藏  举报