问题描述:
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
解题思路:
特点:
先序遍历的第一个节点为树根节点
中序遍历中依据先序遍历的根节点可以将整棵树分割为左子树和右子树两个部分
1、通过先序遍历找到第一个点作为根节点,在中序遍历中找到根节点并记录rootIndex。
2、记录左子树的长度并在先序遍历中依据这个长度找到左子树的区间,用同样方法可以找到右子树的区间。
3、递归的建立左子树和右子树
代码
class Solution {
/*找到根节点,划分为左右子树序列,继续的递归调用,直到所有的节点构造完成
* 1 [2 4 5] [3 6 7] [4 2 5] 1 [6 3 7]
*/
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public TreeNode buildTree(int[] preorder, int[] inorder) {
int preLength = preorder.length;
int inLength = inorder.length;
return buildTree(preorder, 0, preLength-1, inorder, 0, inLength-1);
}
public TreeNode buildTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd) {
if(preStart > preEnd||inStart > inEnd) {
return null;
}
int rootVal = preorder[preStart];
int rootIndex = 0;
//在中序遍历序列中找到根节点的值
for(int i = inStart; i <= inEnd; i++) {
if(rootVal == inorder[i]) {
rootIndex = i;
break;
}
}
TreeNode root = new TreeNode(rootVal);
//找到左子树的长度
int len = rootIndex - inStart;
//将先序序列和中序序列分别分割为左子树的部分,继续调用
root.left = buildTree(preorder, preStart+1, preStart+len, inorder, inStart, rootIndex-1);
//将先序序列和中序序列分别分割为右子树的部分,继续调用
root.right = buildTree(preorder, preStart+len+1, preEnd, inorder, rootIndex+1, inEnd);
return root;
}
}