题目:
105. Construct Binary Tree from Preorder and Inorder Traversal
解题思路:
根据定义,每次从前序中取出根节点,找出根节点在中序中的位置,递归处理。
难点在下一次递归函数中的左右下标位置。
代码: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
26public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder == null || inorder == null
|| preorder.length <= 0 || inorder.length <= 0
|| preorder.length != inorder.length) return null;
return construct(0,preorder.length - 1,preorder,0,inorder.length-1,inorder);
}
private TreeNode construct(int prel,int prer,int[] pre,int ml,int mr,int[] mid){
TreeNode root = new TreeNode(pre[prel]);
if(prel == prer && ml == mr) return root;
int index = ml;
while(root.val != mid[index] && index <= mr){
index ++;//中序中根结点的位置
}
int leftcount = index - ml;
if(leftcount > 0){
root.left = construct(prel+1,prel+leftcount,pre,ml,index-1,mid);
}
if(leftcount < mr - ml){
root.right = construct(prel+leftcount+1,prer,pre,index+1,mr,mid);
}
return root;
}