105. Construct Binary Tree from Preorder and Inorder Traversal

来源:互联网 发布:苹果mac自有办公软件 编辑:程序博客网 时间:2024/07/17 22:13
class Solution {public:    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {        if(0 == preorder.size() || 0 == inorder.size()) return NULL;        return build(preorder, inorder, 0, inorder.begin(), inorder.end());    }    TreeNode *build(vector<int>& preorder, vector<int>& inorder, int rootPreIndex, vector<int>::iterator Instart,               vector<int>::iterator Inend)    {        if(rootPreIndex >= preorder.size() || Inend <= Instart) return NULL;        auto target = find(Instart, Inend, preorder[rootPreIndex]);        if(target != inorder.end()){             TreeNode *root = new TreeNode(preorder[rootPreIndex]);             root->left = build(preorder, inorder, rootPreIndex+1, Instart, target);             root->right = build(preorder, inorder, rootPreIndex + target - Instart + 1, target+1, Inend);             return root;        }        else{            return NULL;        }    }};

阅读全文
0 0