美文网首页
106. Construct Binary Tree from

106. Construct Binary Tree from

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

题目链接

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

代码

class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return dfs(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1);

    }

    TreeNode* dfs(vector<int>& inorder, int is, int ie, vector<int>& postorder, int ps, int pe) {
        if (is > ie) {
            return NULL;
        }
        int val = postorder[pe];
        TreeNode *parent = new TreeNode(val);
        int ii = is, pi = ps;
        while (ii <= ie && val != inorder[ii]) {
            ii++;
            pi++;
        }
        parent->left = dfs(inorder, is, ii - 1, postorder, ps, pi - 1);
        parent->right = dfs(inorder, ii + 1, ie, postorder, pi, pe - 1);
        return parent;
    }
};

相关文章

网友评论

      本文标题:106. Construct Binary Tree from

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