输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
思路
根据中序遍历和前序遍历可以确定二叉树,具体过程为:
1.根据前序序列第一个结点确定根结点
2.根据根结点在中序序列中的位置分割出左右两个子序列
3.对左子树和右子树分别递归使用同样的方法继续分解
例如:
前序序列{1,2,4,7,3,5,6,8} = pre
中序序列{4,7,2,1,5,3,8,6} = in
根据当前前序序列的第一个结点确定根结点,为 1
找到 1 在中序遍历序列中的位置,为 in[3]
切割左右子树,则 in[3] 前面的为左子树, in[3] 后面的为右子树
则切割后的左子树前序序列为:{2,4,7},切割后的左子树中序序列为:{4,7,2};切割后的右子树前序序列为:{3,5,6,8},切割后的右子树中序序列为:{5,3,8,6}
对子树分别使用同样的方法分解
5.22 自己又写了一遍
/**
* Definition for a binary tree node.
* public 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 != inorder.length) return null;
if(preorder.length==0 || inorder.length==0) return null;
TreeNode root = new TreeNode(preorder[0]);
for(int i=0;i<preorder.length;i++){
if(preorder[0]==inorder[i]){
root.left=buildTree(Arrays.copyOfRange(preorder,1,i+1),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;
}
}
之前的
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.Arrays;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if (pre.length == 0 || in.length == 0) {
return null;
}
TreeNode root = new TreeNode(pre[0]);
// 在中序中找到前序的根
for (int i = 0; i < in.length; i++) {
if (in[i] == pre[0]) {
// 左子树,注意 copyOfRange 函数,左闭右开
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, i + 1), Arrays.copyOfRange(in, 0, i));
// 右子树,注意 copyOfRange 函数,左闭右开
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, i + 1, pre.length), Arrays.copyOfRange(in, i + 1, in.length));
break;
}
}
return root;
}
}
3.24 自己又写了一遍
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
import java.util.*;
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
int len = pre.length;
TreeNode sroot = creatTree(0, 0, len - 1, pre, in);
return sroot;
}
private TreeNode creatTree(int root, int beg, int end,int[] pre, int[] in) {
if (beg > end) return null;
TreeNode node = new TreeNode(pre[root]);
int loc = 0;
int cnt = 0;
for (loc = beg; loc <= end; loc++) {
cnt++;
if (pre[root] == in[loc])
break;
}
node.left = creatTree(root + 1, beg, loc - 1,pre, in);
node.right = creatTree(root + cnt, loc + 1, end, pre, in);
return node;
}
}
总结
一、根据中序遍历和前序遍历可以确定二叉树,具体过程要记住
1.根据前序序列第一个结点确定根结点
2.根据根结点在中序序列中的位置分割出左右两个子序列
3.对左子树和右子树分别递归使用同样的方法继续分解
二、
建立新的根节点 TreeNode root= new TreeNode(pre[0]);
三、递归思想
1.终止条件
if(pre.length0||in.length0)
return null;
2.循环 找到中序遍历数组根节点对应位置后
左子树 为 pre in (注意边界坐标)
右子树 为 pre in
最后返回root根节点
四、Arrays.copyOfRange(in, i + 1, in.length)
函数左开右闭