Easy Java Solution

  • 0

    public class Solution {

    public TreeNode buildTree(int[] preorder, int[] inorder) {
          if (preorder.length == 0) return null;
          Map<Integer, Integer> pos = new HashMap<Integer, Integer>();
          int i = 0;
          for (int num: inorder) pos.put(num, i++);
          return build(preorder, inorder, new TreeNode(0), 0, inorder.length-1, pos);
    public TreeNode build(int[] preorder, int[] inorder, TreeNode pre, int inst, int inend, Map<Integer, Integer> pos) {
        if (inend < inst) return null;
        int preSt = pre.val;
        TreeNode root = new TreeNode(preorder[preSt]);
        int index = pos.get(root.val);
        root.left = build(preorder, inorder, pre, inst, index-1, pos);
        root.right = build(preorder, inorder, pre, index+1, inend, pos);
        return root;


Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.