The key to this problem is to know what we need to know for recursion. For example, we need to know the position of the root node of the left subtree in the original preorder sequence is pre_root + 1, and then we need to know the position of the left subtree in the original preorder sequence, which can be obtained according to the traversal rule of the binary tree.So to summarize, to locate the left subtree, we need to know three index positions, and the same goes for the right subtree.
What’s a little harder to understand here is the index of the root node of the right subtree in the preorder sequence: the index of the root node + the length of the left subtree +1
solution
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
class TreeNode{
public int key;
public TreeNode left;
public TreeNode right;TreeNode(int x){ key = x;}
public voidtraversal(TreeNode t){if(t != null){traversal(t.left);
System.out.println(t.key);traversal(t.right);}}}
class Solution{
HashMap<Integer, Integer> dic = new HashMap<>();int[] po;
public TreeNode buildTree(int[] preorder,int[] inorder){
po = preorder;for(int i =0; i < inorder.length; i++)
dic.put(inorder[i], i);//put inorder into mapreturnrecur(0,0, inorder.length -1);}
TreeNode recur(int pre_root,int in_left,int in_right){if(in_left > in_right)return null;
TreeNode root = new TreeNode(po[pre_root]);int i = dic.get(po[pre_root]);
root.left =recur(pre_root +1, in_left, i -1);
root.right =recur(pre_root + i - in_left +1, i +1, in_right);return root;}
public staticvoidmain(String[] args){
Solution s = new Solution();int[] pre ={3,9,20,15,7};int[] in ={9,3,15,20,7};
TreeNode t = s.buildTree(pre, in);
t.traversal(t);//use inorder traversal to testify the result.}}//this solution is extracted from ://https://leetcode-cn.com/problems/zhong-jian-er-cha-shu-lcof/solution/mian-shi-ti-07-zhong-jian-er-cha-shu-di-gui-fa-qin/
Problem DescriptionanalysisThe key to this problem is to know what we need to know for recursion. For example, we need to know the position of the root node of the left subtree in the original preorder sequence is pre_root + 1, and then we need to know