题目
题目:已知某二叉树的前序遍历序列与中序便利序列,请重建该二叉树。假设前序遍历序列与中序遍历序列的结果中不包含重复数字。
前序遍历序列:{1,2,4,7,3,5,6,8}
中序遍历序列:{4,7,2,1,5,3,8,6}
思路
前序遍历就是:根节点——>左子树——>右子树,所以我们可以知道前序遍历序列中的第一个元素就是根节点root
中序遍历就是:左子树——>根节点——>右子树,由于在前序遍历序列中已经找到了根节点root,我们在中序遍历序列中找与根节点值相同的节点,找到之后根节点左面的序列就是左子树,根节点右面的序列就是右子树
假如在中序遍历序列中根节点左面有m个元素,则在前序遍历序列中根节点之后的m个元素就是左子树(按上面的步骤递归处理该子树),之后就全部是右子树(处理方法同左子树)
java代码
package com.cn;
//二叉树结点
class Node{
int value;
Node leftTree;
Node rightTree;
public Node(){
}
public Node(int value){
this.value = value;
this.leftTree = null;
this.rightTree = null;
}
public Node(int value, Node leftTree, Node rightTree){
this.value = value;
this.leftTree = leftTree;
this.rightTree = rightTree;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getLeftTree() {
return leftTree;
}
public void setLeftTree(Node leftTree) {
this.leftTree = leftTree;
}
public Node getRightTree() {
return rightTree;
}
public void setRightTree(Node rightTree) {
this.rightTree = rightTree;
}
}
public class BuildTwoForkTree {
public static void main(String[] args) {
int[] startPreorder = new int[]{1,2,4,7,3,5,6,8};
int[] midPreorder = new int[]{4,7,2,1,5,3,8,6};
Node root = BuildTree(startPreorder,0,startPreorder.length - 1,midPreorder,0,midPreorder.length-1);
PrintTree(root);
}
//根据前序遍历序列及中序遍历序列创建二叉树
public static Node BuildTree(int[] a,int startA,int endA,int[] b,int startB,int endB){
if(startA > endA || startB > endB){
return null;
}
Node root = new Node(a[startA]);
// 在中序遍历序列中寻找根节点
int i = startB;
for(;i <= endB;i++){
if(b[i] == a[startA])
break;
}
//根节点往左是左子树,定义左子树的长度
int offSet = i - startB;
//左子树
root.leftTree = BuildTree(a,startA+1,startA+offSet,b,startB,startB + offSet-1);
//右子树
root.rightTree = BuildTree(a,startA+offSet+1,endA,b,startB+offSet+1,endB);
return root;
}
//递归输出二叉树的前序遍历
public static void PrintTree(Node root){
if(root == null){
return;
}
System.out.print(root.value + " ");
PrintTree(root.leftTree);
PrintTree(root.rightTree);
}
//非递归输出二叉树的前序遍历
public static void PrintTree1(Node root){
}
}