Skip to content

Commit

Permalink
problem7
Browse files Browse the repository at this point in the history
  • Loading branch information
cris1313 committed Jun 30, 2017
1 parent a34b905 commit 3955474
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
46 changes: 46 additions & 0 deletions Problem7/ConstructTree.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
/**
* Created by owen on 2017/6/30.
*/
public class ConstructTree {
public PBinaryTreeNode constructCore(int[] pre, int[] in) {
if (pre.length!=in.length||pre==null||in==null){
//无效输入 抛出异常
}
return constructCore(pre, in, 0, pre.length - 1, 0, in.length - 1);
}

private PBinaryTreeNode constructCore(int[] pre, int[] in, int startPre, int endPre, int startIn, int endIn) {
if (startPre>endPre||startIn>endIn||endPre-startPre!=endIn-startIn) {
//无效输入 抛出异常
}
PBinaryTreeNode root = new PBinaryTreeNode();
int rootVal = pre[startPre];
root.value = rootVal;
root.left = root.right = root.parent = null;
//递归基本条件
if (startPre == endPre) {
if (endIn == startIn && pre[startPre] == in[startIn]) {
return root;
} else {//抛出异常
}
}
//在中序遍历中找到rootVal
int rootIn = startIn;
while(in[rootIn]!=rootVal&&rootIn<endIn)
++rootIn;
if (in[rootIn]!=rootVal&&rootIn==endIn) {
//抛出异常
}

//构建左子树
int length = rootIn-startIn;
if(length>0){
root.left= constructCore(pre,in,startPre+1,startPre+length,startIn,rootIn-1);
}
//构建右子树
if (length<endPre-startPre){
root.right = constructCore(pre,in,startPre+length+1,endPre,rootIn+1,endIn);
}
return root;
}
}
14 changes: 14 additions & 0 deletions Problem7/Trst7.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* Created by owen on 2017/6/30.
*/
public class Trst7 {
public static void main(String[] args) {
int[] pre={1,2,4,7,3,5,6,8};
int[] in = {4,7,2,1,5,3,8,6};
ConstructTree constructTree = new ConstructTree();
PBinaryTreeNode root = constructTree.constructCore(pre,in);
//先序遍历验证
PBinaryTreeNode.preOrder(root);
}

}
15 changes: 15 additions & 0 deletions util/PBinaryTreeNode.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* Created by owen on 2017/6/30.
*/
public final class PBinaryTreeNode {
PBinaryTreeNode left;
PBinaryTreeNode right;
PBinaryTreeNode parent;
int value;
public static void preOrder(PBinaryTreeNode root){
if(root==null)return;
System.out.println(root.value);
preOrder(root.left);
preOrder(root.right);
}
}

0 comments on commit 3955474

Please sign in to comment.