输入一棵二叉树前序遍历和中序遍历的结果,请重建该二叉树。
注意:
二叉树中每个节点的值都互不相同;
输入的前序遍历和中序遍历一定合法;
样例
给定:
前序遍历是:[3, 9, 20, 15, 7]
中序遍历是:[9, 3, 15, 20, 7]
返回:[3, 9, 20, null, null, 15, 7, null, null, null, null]
返回的二叉树如下所示:
3
9 20
15 7
算法
前序遍历数组第一个元素为当前根,再中序遍历中查找这个元素,这个元素前面的元素就是左子树元素,右边为右子树元素,进行递归调用构造整颗二叉树。
例如:
前序遍历是:[3, 9, 20, 15, 7]
中序遍历是:[9, 3, 15, 20, 7]
前序遍历第一个元素是3,说明3是根节点,再根据中序遍历数组可得左子树为[9],右子树为[15,20,7]
这时左子树前序遍历是:[9],中序遍历是[9]
右子树前序遍历是:[20, 15, 7]],中序遍历是 [15, 20, 7]
对左右子树依次进行递归调用…
/**
* Definition for a binary tree node.
* class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder.length == 0 || inorder.length == 0){
return null;
}
TreeNode root = new TreeNode(preorder[0]);
for(int i = 0;i < inorder.length;i++){
if(inorder[i] == preorder[0]){
//构建左子树
root.left = buildTree(Arrays.copyOfRange(preorder,1,1+i),Arrays.copyOfRange(inorder,0,i));
//构建右子树
root.right = buildTree(Arrays.copyOfRange(preorder,i+1,preorder.length),Arrays.copyOfRange(inorder,i+1,inorder.length));
break;
}
}
return root;
}
}