The topic is from LeetCode
105. Construct a binary tree from preorder and middle order traversal sequence
Other solutions or source code can be accessed: tongji4m3
description
The binary tree is constructed according to the pre-order and middle-order traversal of a tree.
Note:
You can assume that there are no duplicate elements in the tree.
例如,给出
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
Ideas
For the array [lo,hi] traversed in pre-order and middle-order:
- The root node of the preorder is lo, and the root node of the middle order is i
- The left subtree of the preorder is [lo+1,i], the right subtree is [i+1,hi]
- The left subtree of the middle order is [lo,i-1], and the right subtree is [i+1,hi]
Therefore, the root node can be constructed first, and then his left and right nodes can be constructed according to the left and right arrays in the pre-order, middle-order, and continue to recurse...
detail
- Note that the pre-order after several recursion, the middle-order array may not be symmetrical up and down, so their index index must be divided into preIndex, inIndex
- Use map storage to speed up
Code
/**
* look 用map存储加快速度
树中没有重复元素
用map存储inorder数组的值和对应索引
方便找到根节点位置
*/
private Map<Integer, Integer> map = new HashMap<>();
public TreeNode buildTree(int[] preorder, int[] inorder)
{
for (int i = 0; i < inorder.length; i++)
{
map.put(inorder[i], i);
}
return buildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
}
private TreeNode buildTree(int[] preorder, int preLo, int preHi, int[] inorder, int inLo, int inHi)
{
if (preLo > preHi || inLo > inHi)
{
return null;
}
//找到根节点在中序遍历的索引位置
int inIndex = map.get(preorder[preLo]);
//look,i在经过几次之后,只是对应了inorder的i,但是对于preorder,应该只是一个偏移量
//inIndex - inLo代表左子树的个数,preIndex则是前序遍历左子树的最后一个元素
int preIndex = preLo + inIndex - inLo;
TreeNode root = new TreeNode(preorder[preLo]);
root.left = buildTree(preorder, preLo + 1, preIndex, inorder, inLo, inIndex - 1);
root.right = buildTree(preorder, preIndex + 1, preHi, inorder, inIndex + 1, inHi);
return root;
}