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
中序遍历的顺序是:左子树,root,右子树
根据前序遍历数组我们已经知道了root
根据这个root可以在中序遍历数组中找到root对应的位置rootIdx
几个变量:
前序遍历数组的第一个元素位置记为preStart
中序遍历数组的开始位置和结束位置记为:inStart, inEnd
同时可以知道因为inorder和preorder数组的size是一样的,所以inEnd也代表了preorder数组的结束位置
现在可以知道在中序遍历数组中从inStart到rootIdx-1是左子树,rootIdx+1到inEnd是右子树
同时也可以知道左子树的size是rootIdx - inStart + 1
前序遍历的顺序是:root, 左子树,右子树
现在前序遍历数组中从preStart+1到preStart+左子树size的范围是左子树
而左子树范围的第一个元素是左子树的root,然后再按上述步骤递归左子树范围的数组
同理preorder数组中preStart+左子树size+1到inEnd的范围为右子树的范围,
而右子树范围的第一个元素是右子树的root,然后递归右子树范围的数组
public TreeNode buildTree(int[] preorder, int[] inorder) {
if (preorder == null || inorder == null) {
return null;
}
return buildTreeHelper(preorder, inorder, 0, 0, inorder.length - 1);
}
public TreeNode buildTreeHelper(int[] preorder, int[] inorder, int preStart,
int inStart, int inEnd) {
if (preStart >= preorder.length || inStart > inEnd) {
return null;
}
int rootIdx = inStart;
TreeNode root = new TreeNode(preorder[preStart]);
while (rootIdx < inEnd) {
if (inorder[rootIdx] == preorder[preStart]) {
break;
}
rootIdx ++;
}
root.left = buildTreeHelper(preorder, inorder, preStart + 1, inStart, rootIdx - 1);
root.right = buildTreeHelper(preorder, inorder, preStart + rootIdx - inStart + 1,
rootIdx + 1, inEnd);
return root;
}
或者
public TreeNode buildTree(int[] preorder, int[] inorder) {
return build(preorder, inorder, 0, preorder.length-1, 0, inorder.length-1);
}
TreeNode build(int[] preorder, int[] inorder, int preS, int preE, int inS, int inE) {
if(preS > preE || inS > inE) return null;
int rootVal = preorder[preS];
TreeNode root = new TreeNode(rootVal);
int leftLen = 0;
for(int i = inS; i < inE; i++) {
if(inorder[i] == rootVal) break;
leftLen ++;
}
root.left = build(preorder, inorder, preS+1, preS+leftLen, inS, inS+leftLen-1);
root.right = build(preorder, inorder, preS+leftLen+1, preE, inS+leftLen+1, inE);
return root;
}