[LeetCode] 105. Construct Binary Tree from Preorder and Inorder Traversal
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
You may assume that duplicates do not exist in the tree.
Thought process:
Iterate through the preorder array. Find the element in the inorder array. The elements to the left are the left subtree and the elements to the right are the right subtree. Recurse down to next level. The base case happens when preorder's index >= preorder.length or when left > right end of inorder array.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < inorder.length; i++) { map.put(inorder[i], i); } return buildTree(preorder, map, 0, 0, inorder.length - 1); } private TreeNode buildTree(int[] preorder, Map<Integer, Integer> map, int preIndex, int left, int right) { if (preIndex >= preorder.length || left > right) { return null; } int value = preorder[preIndex]; int inIndex = map.get(value); TreeNode node = new TreeNode(value); node.left = buildTree(preorder, map, preIndex + 1, left, inIndex - 1); node.right = buildTree(preorder, map, preIndex + inIndex - left + 1, inIndex + 1, right); return node; } } |
Time complexity: O(n).
Comments
Post a Comment