您的位置:首页 > Web前端

《剑指offer》006-重建二叉树

2017-03-21 10:01 387 查看
题目:输入前序和中序,重建二叉树。(假设前序和中序不含重复数字)。

public class ConstructBiTree {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] pre = {1,2,4,7,3,5,6,8};
int[] in = {4,7,2,1,5,3,8,6};
//      int[] pre = {1,2};
//      int[] in = {2,1};
if((pre.length < 1) || (pre.length != in.length)){
System.out.println("Invalid input, cannot find a tree.");
}
ConstructBiTree c = new ConstructBiTree();
BiTreeNode root = c.construct(pre, in);
System.out.print("preorder: ");
c.t(root);
}

private void t(BiTreeNode node) {
// TODO Auto-generated method stub
if(node != null){
System.out.print(node.data + " ");
t(node.left);
t(node.right);
}
}
public BiTreeNode construct(int[] pre,int[] in){
if(pre.length == 0 || pre.length != in.length){
return null;
}
return constructCore(pre, 0, pre.length-1, in, 0, in.length-1);
}
public BiTreeNode constructCore(int[] pre, int p, int q, int[] in, int i, int j){
BiTreeNode root = new BiTreeNode(pre[p]);
root.left = null;
root.right = null;
if(p == q){
if(i == j && pre[p] == in[i]){
return root;
}else{
System.out.println("Invalid input, cannot find a tree.");
//throws exception
}
}
int rootInorder = i;
while(pre[p] != in[rootInorder] && rootInorder <= j){
rootInorder++;
}
if(rootInorder == j && pre[p] != in[rootInorder]){
System.out.println("Invalid input, cannot find a tree.");
//throws exception
}
int leftLength = rootInorder - i;
int leftPreorderEnd = p +leftLength;
if(leftLength > 0){
root.left = constructCore(pre, p+1, leftPreorderEnd, in, i, rootInorder-1);
}
if(q - p - leftLength > 0){
root.right = constructCore(pre, leftPreorderEnd+1, q, in, rootInorder+1, j);
}
return root;
}
class BiTreeNode{
int data;
BiTreeNode left;
BiTreeNode right;
public BiTreeNode(int data){
this.data = data;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: