LeetCode-Construct Binary Tree from Preorder and Inorder Traversal

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

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

class Solution {
public:
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);
    }
};

注意:在利用递归算法解题时要注意节省内存。最初觉得通过传递下标参数计算麻烦,而试图每次重新构造vector数据进行参数传递,如下所示:

        if (rootIndex!=0)
        {
            vector<int>p(preorder.Begin()+1, preorder.Begin()+rootIndex+1);
            vector<int>q(inorder.Begin(), inorder.Begin()+rootIndex);
            root->left = buildTree(p,q);
        }

这么做有两个问题:
1. 在用迭代器初始化vector时,第二个迭代器要指向有效数据的下一个数;
2. 容易造成内存溢出的问题。(在leetcode中运行时就出现这个问题)。

posted @ 2015-05-19 13:37  Rosanne  阅读(148)  评论(0编辑  收藏  举报