A binary tree is constructed according to the preorder traversal and the middle order traversal of a tree.
Be careful:
You can assume that there are no duplicate elements in the tree.
For example, give
Preorder traversal preorder = [3,9,20,15,7] Middle order traversal inorder = [9,3,15,20,7]
Return the following binary tree:
3 / \ 9 20 / \ 15 7
Train of thought:
(1) the first node traversed by the preamble is the root node
(2) according to the position of the root node in the middle order traversal, the left and right subtrees are divided
③ determine the range limits of left and right subtrees in preorder traversal and inorder traversal
④ recursive execution
Code:
/** * 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) { if(preorder.length == 0){ return null; } java.util.Map<Integer,Integer> map = new java.util.HashMap<>(); for(int i = 0;i < inorder.length;i++){ map.put(inorder[i],i); } return buildNode(preorder,0,preorder.length-1,inorder,0,inorder.length-1,map); } public TreeNode buildNode(int[] preorder,int begin1,int end1, int[] inorder,int begin2,int end2, java.util.Map<Integer,Integer> map){ if(begin1 > end1 || begin2 > end2){ return null; } if(begin1 == end1){ return new TreeNode(preorder[begin1]); } TreeNode root = new TreeNode(preorder[begin1]); int index = map.get(preorder[begin1]); root.left = buildNode(preorder,begin1+1,begin1+index-begin2,inorder,begin2,index-1,map); root.right = buildNode(preorder,begin1+1+index-begin2,end1,inorder,index+1,end2,map); return root; } }