leetcode第一刷_Construct Binary Tree from Preorder and Inorder Traversal

构造方式跟中序与后序全然一样,并且一般都习惯正着来,所以更简单。

代码是之前写的,没实用库函数,不应该。

TreeNode *buildIt(vector<int> &preorder, int start1, vector<int> &inorder, int start2, int len){
    if(len <= 0)
        return NULL;
    TreeNode *root = new TreeNode(preorder[start1]);
    int i = start2;
    for(;i<start2+len&&inorder[i] != preorder[start1];i++);
    int len2 = i-start2;
    root->left = buildIt(preorder, start1+1, inorder, start2, len2);
    root->right = buildIt(preorder, start1+1+len2, inorder, i+1, len-len2-1);
    return root;
}

class Solution {
public:
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        if(preorder.size()<=0 || inorder.size()<=0)
            return NULL;
        return buildIt(preorder, 0, inorder, 0, preorder.size());
    }
};


posted @ 2014-07-08 13:55  hrhguanli  阅读(123)  评论(0编辑  收藏  举报