Construct Binary Tree from Preorder and Inorder Traversal ---LeetCode

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

解题思路:

由于先序遍历(DLR)可以知道根节点的位置,而中序遍历(LDR)可以知道左子树右子树的位置,就可以用递归来实现。记住并理解递归的参数。

举个例子:
preorder: [7, 10, 4, 3, 1, 2, 8, 11]
inorder: [4, 10, 3, 1, 7, 11, 8, 2]

示意图:
Construct Binary Tree from Preorder and Inorder Traversal ---LeetCode_第1张图片

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || inorder == null) return null;

        HashMap map = new HashMap<>();
        for (int i=0; ireturn helper(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, map);
    }
    public TreeNode helper(int[] preorder, int preL, int preR, int[] inorder, int inL, int inR, HashMap map) {
        if (preL > preR || inL > inR) return null;

        TreeNode root = new TreeNode(preorder[preL]);
        int index = map.get(root.val);

        root.left  = helper(preorder, preL + 1, index - inL + preL, inorder, inL, index - 1, map);
        root.right = helper(preorder, index - inL + preL + 1, preR, inorder, index + 1, inR, map);

        return root;
    }
}

你可能感兴趣的:(Leetcode,递归,leetcode,java,算法,面试)