详细的代码可见github:
https://github.com/AbitGo/myClassWork/tree/master/workspace_ds
节点类实现:
package com.company.ch5;
public class BiTreeNode {
public Object data;
public BiTreeNode lchild,rchild;
//构造一个空节点
public BiTreeNode(){
this(null);
}
//构造一颗左右子域为空的二叉树
public BiTreeNode(Object data){
this(data,null,null);
}
//构建一个数据域和左、右孩子域都不为空的二叉树
public BiTreeNode(Object data,BiTreeNode lchild,BiTreeNode rchild){
this.data = data;
this.lchild = lchild;
this.rchild = rchild;
}
}
树的实现
package com.company.ch5;
import com.company.ch3.Stack.SqStack.SqStack;
import com.company.ch3.queue.LinkSqeue;
public class BiTree {
private BiTreeNode root;
//通过先根+中根/后根+中根建立
public BiTree(String preOrder, String inOrder, int preIndex, int inIndex, int count) {
if (count > 0) {
char r = preOrder.charAt(preIndex);
int i = 0;
for(;i<count;i++){
if(r==inOrder.charAt(i+inIndex)){
break;
}
}
root = new BiTreeNode(r);
root.lchild = new BiTree(preOrder,inOrder,preIndex+1,inIndex,i).root;
root.rchild = new BiTree(preOrder,inOrder,preIndex+i+1,inIndex+i+1,count-i-1).root;
}
}
//由标明空子树的先根遍历创建一颗二叉树
public BiTree(String preStr){
if(constant.index_len<=preStr.length()){
char c = preStr.charAt(constant.index_len++);
if(c!='#'){
root = new BiTreeNode(c);
root.rchild = new BiTree(preStr).root;
root.lchild = new BiTree(preStr).root;
}else {
root = null;
}
}
}
//由完全二叉树的顺序存储结构建立其二叉链式存储结构
public BiTreeNode createBiTree_method(String sqBiTree,int index){
BiTreeNode root = null;
if(index<sqBiTree.length()){
root = new BiTreeNode(sqBiTree.charAt(index));
root.lchild = createBiTree_method(sqBiTree,index*2+1);
root.rchild = createBiTree_method(sqBiTree,index*2+2);
}
return root;
}
public BiTreeNode getRoot() {
return root;
}
public void setRoot(BiTreeNode root) {
this.root = root;
}
public static int getIndex() {
return index;
}
public static void setIndex(int index) {
BiTree.index = index;
}
//构建一颗空树
public BiTree() {
this.root = null;
}
//构造一颗树
public BiTree(BiTreeNode root) {
this.root = root;
}
//用于记录preStr的索引值
private static int index = 0;
}