LeetCode105——从前序与中序遍历序列构造二叉树

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/description/

题目描述:

LeetCode105——从前序与中序遍历序列构造二叉树_第1张图片

知识点:根据前序与中序遍历重建二叉树

思路:前序遍历决定根节点,中序遍历区分左右子树

和PAT-ADVANCED1043——Is It a Binary Search Tree中重建二叉树的过程是一致的。

时间复杂度和空间复杂度均是O(N)。

JAVA代码:

public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        TreeNode root = create(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1);
        return root;
    }

    private TreeNode create(int[] preorder, int[] inorder, int preLeft, int preRight, int inLeft, int inRight) {
        if(preLeft > preRight){
            return null;
        }
        TreeNode treeNode = new TreeNode(preorder[preLeft]);
        int k = 0;
        for(int i = inLeft; i <= inRight; i++){
            if(inorder[i] == preorder[preLeft]){
                k = i;
                break;
            }
        }
        int numLeft = k - inLeft;
        treeNode.left = create(preorder, inorder, preLeft + 1, preLeft + numLeft, inLeft, k - 1);
        treeNode.right = create(preorder, inorder, preLeft + numLeft + 1, preRight, k + 1, inRight);
        return treeNode;
    }
}

LeetCode解题报告:

LeetCode105——从前序与中序遍历序列构造二叉树_第2张图片

 

你可能感兴趣的:(LeetCode题解)