美文网首页
105. Construct Binary Tree from

105. Construct Binary Tree from

作者: jecyhw | 来源:发表于2019-06-12 06:27 被阅读0次

    题目链接

    https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/

    代码

    class Solution {
    public:
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
            int pi = 0;
            return dfs(preorder, pi, inorder, 0, inorder.size() - 1);
        }
    
        TreeNode* dfs(vector<int>& preorder, int &pi, vector<int>& inorder, int is, int it) {
            if (is > it) {
                return NULL;
            }
            int val = preorder[pi];
            TreeNode *parent = new TreeNode(val);
            int pos = is;
            while (pos <= it && val != inorder[pos]) {
                pos++;
            }
            pi++;
            parent->left = dfs(preorder, pi, inorder, is, pos - 1);
            parent->right = dfs(preorder, pi, inorder, pos + 1, it);
            return parent;
        }
    };
    

    相关文章

      网友评论

          本文标题:105. Construct Binary Tree from

          本文链接:https://www.haomeiwen.com/subject/blwhfctx.html