题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
思路:
根据先序遍历可以得到根节点
根据中序遍历可以得到左节点和右节点
才后采用递归可以得到我们想要的答案
定义一棵TreeNode
package 重建二叉树;
public class TreeNode{
int val;
public TreeNode left;
public TreeNode right;
TreeNode(int x) {
val = x;
}
}
package 重建二叉树;
/**
* 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。
* @author 龙哥
*/
//思路分析:首先应该知道在先序遍历:头左右 中序遍历:左根右 后序遍历:左右根
//根据先序需要得到二叉树的根 根据中序遍历可以得到二叉树的左节点集合 右节点集合
//如果我们把左子树和右子树分别作为新的二叉树,则可以求出其根节点,左子树和右子树。
//然后利用递归的思想实现二叉树的重建
//首先定义二叉树
public class Solution {
//根据先序和终序
public static TreeNode reConstructTreeNode(int[] pre,int[] in){
if (pre == null || in== null) {
return null;
}
TreeNode mm = reConstuctBinaryTreeCore(pre,0,pre.length - 1,in,0,in.length - 1);
return mm;
}
private static TreeNode reConstuctBinaryTreeCore(int[] pre, int preStart, int preEnd, int[] in, int inStart, int inEnd) {
TreeNode tree = new TreeNode(pre[preStart]);
tree.left = null;
tree.right = null;
//如果左右节点不存在,则该二叉树直接构建成功
if (preStart == preEnd || inStart == inEnd) {
return tree;
}
//寻找根节点
int root = 0;
for(root = inStart; root < inEnd; root++){
if (pre[preStart] == in[root]) {
break;
}
//寻找左右节点,进行构建
int leftLength = root - inStart;
int rightLength = inEnd- root;
//使用递归
if (leftLength > 0) {
tree.left = reConstuctBinaryTreeCore(pre, preStart + 1, preStart + leftLength, in, inStart, root - 1);
}
if (rightLength > 0) {
tree.right = reConstuctBinaryTreeCore(pre, preStart + 1 + leftLength, preEnd, in, root + 1, inEnd);
}
}
return tree;
}
public static void postTraverseBinTree(TreeNode node){
if (node==null) {
return;
}
if (node.left!=null) {
postTraverseBinTree(node.left);
}
if(node.right!=null){
postTraverseBinTree(node.right);
}
System.out.print(node.val+",");
}
public static void main(String[] args){
int pre[] = {1,2,4,7,3,5,8,9,6};
int in[] = {4,7,2,1,8,5,9,3,6};
TreeNode tree = reConstructTreeNode(pre, in);
System.out.print("中序遍历结果: {");
postTraverseBinTree(tree);
System.out.println("}");
}
}
但是很遗憾,这样的写法在考试提交编译的时候会提示超时!!
下面我们优化一波
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre == null || in == null){
return null;
}
TreeNode root = reConstructBinaryTreeCore(pre,0,pre.length - 1,in,0,in.length - 1);
return root;
}
private TreeNode reConstructBinaryTreeCore(int[] pre,int preStart,int preEnd,int[] in,int inStart,int inEnd){
if(preStart > preEnd || inStart > inEnd){
return null;
}
TreeNode root = new TreeNode(pre[preStart]);
for(int i = inStart; i <= inEnd; i++){
if(in[i] == pre[preStart]){
root.left = reConstructBinaryTreeCore(pre,preStart + 1,preStart + i - inStart,in, i - 1, i);
root.right = reConstructBinaryTreeCore(pre,i - inStart + preStart + 1,preEnd,in,i + 1,inEnd);
}
}
return root;
}
}