题目
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
思路
- 前序遍历的第一个为root节点(3),找到中序遍历该节点,以此划分左右子树; 9|3|15,20,7;
- 根据上面的划分同时划分前序数组 3|9|20,15,7,则判断出左子树是一个单独的9,而右子树的根节点为20;
- 根据中序遍历的特点继续第一步,根据右子树的根节点(20)划分右子树的左右-->递归
递归:左子树sub数组,右子树sub数组
代码
public TreeNode buildTree(int[] preorder, int[] inorder) {
TreeNode root = null;
if (preorder.length == 0 || inorder.length == 0) {
return root;
}
root = new TreeNode(preorder[0]);
int tmp = 0;
for (int i = 0; i < inorder.length; i++) {
tmp = i;
if(preorder[0] == inorder[i]){
break;
}
}
int[] leftInorder = Arrays.copyOfRange(inorder,0,tmp);
int[] rightInorder = Arrays.copyOfRange(inorder,tmp+1,inorder.length);
int[] leftPreorder = Arrays.copyOfRange(preorder,1,1+tmp);
int[] rightPreorder = Arrays.copyOfRange(preorder,tmp+1,preorder.length);
root.left = buildTree(leftPreorder,leftInorder);
root.right = buildTree(rightPreorder,rightInorder);
return root;
}
网友评论