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
 

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

class Solution {
    Map inMap;
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        int n = inorder.length;
        inMap = new HashMap<>();
        //假设元素不重复
        for (int i = 0; i < n; i++) inMap.put(inorder[i],i);
        return build(preorder, 0, n - 1, inorder, 0, n - 1);
    }

    public TreeNode build(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) {
        //终止条件
        if (preStart > preEnd || inStart > inEnd) return null;
        //获取根节点,根节点在中序遍历的index,左子树长度
        TreeNode root = new TreeNode(preorder[preStart]);
        int inRoot = inMap.get(root.val);
        int numsLeft = inRoot - inStart;
        //构造左子树,右子树
        root.left = build(preorder, preStart + 1, preStart + numsLeft, inorder, inStart, inRoot -1);
        root.right = build(preorder, preStart + numsLeft +1, preEnd, inorder, inRoot + 1, inEnd);
        return root;
    }
}

你可能感兴趣的:(#,树,二叉树,leetcode,算法)