topic
Enter the results of pre-order traversal and mid-order traversal of a binary tree, and please rebuild the binary tree. Assume that the input result of pre-order traversal and middle-order traversal does not contain repeated numbers. link
Ideas
The map records the subscript of the in-order traversal node, so that the subsequent pre-order can locate the position of the in-order traversal through the root node.
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
Map<Integer, Integer> map = new HashMap<>();
int[] preorder;
int[] inorder;
public TreeNode buildTree(int[] preorder, int[] inorder) {
for(int i = 0; i < inorder.length; i++){
map.put(inorder[i], i);
}
this.preorder = preorder;
this.inorder = inorder;
return buildTree(0, 0, inorder.length - 1);
}
TreeNode buildTree(int preIdx, int inLeft, int inRight){
if(inLeft > inRight)return null;
TreeNode root = new TreeNode(preorder[preIdx]);
int inRootIdx = map.get(preorder[preIdx]);
//preIdx的下一个即为左子树根节点
root.left = buildTree(preIdx + 1, inLeft, inRootIdx - 1);
//右子树根节点需要跳过所有左子树的节点,左子树节点一共有inRootIdx - inLeft个
//在去除左子树的根节点preIdx+(1+inRootIdx-inLeft)
root.right = buildTree(preIdx + 1 + inRootIdx - inLeft, inRootIdx + 1, inRight);
return root;
}
}