给定两个整数数组 preorder 和 inorder ,其中 preorder 是二叉树的先序遍历, inorder 是同一棵树的中序遍历,请构造二叉树并返回其根节点。
示例 1:
输入: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
输出: [3,9,20,null,null,15,7]
思路:
前序遍历preorder的第一个元素3是根节点,在中序遍历inorder中,3的左边的左子树,3的右边为右子树。所以用递归实现
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode buildTree(int[] preorder, int[] inorder) {
if(preorder == null || inorder == null || preorder.length == 0 || inorder.length ==0) {
return null;
}
int val = preorder[0];
TreeNode root = new TreeNode(val);
if(preorder.length ==1) {
return root;
}
int flag = 0;
for (int i = 0; i < inorder.length; i++) {
if(inorder[i] == val) {
flag=i;
break;
}
}
// Arrays.copyOfRange包含左边,不包含右
root.left = buildTree(Arrays.copyOfRange(preorder,1,flag+1),Arrays.copyOfRange(inorder,0,flag));
root.right = buildTree(Arrays.copyOfRange(preorder,flag+1,preorder.length),Arrays.copyOfRange(inorder,flag+1,inorder.length));
return root;
}
}