LeetCode新编 105. 从前序与中序遍历序列构造二叉树

题干

根据一棵树的前序遍历与中序遍历构造二叉树。

注意:
你可以假设树中没有重复的元素。

例如,给出

前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]

返回如下的二叉树:

3

/
9 20
/
15 7

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解

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

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder, int preIdx, int inLeftStart, int inRightEnd) {
        if (inRightEnd - inLeftStart == 0) return nullptr;
        
        int val = preorder[preIdx];
        int inIdx = inLeftStart;
        while (inorder[inIdx] != val) {
            inIdx++;
        }
        int inLeftEnd = inIdx;
        int inRightStart = inIdx + 1;
        
        TreeNode *root = new TreeNode(val);
        root->left = buildTree(preorder, inorder, preIdx + 1, inLeftStart, inLeftEnd);
        root->right = buildTree(preorder, inorder, preIdx + 1 + (inLeftEnd - inLeftStart), inRightStart, inRightEnd);
        return root;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_49249294/article/details/108895027