java数据结构之二叉树(二)

2014-11-24 03:24:25 · 作者: · 浏览: 1
if (root!=null)
return root.getData();
else
return null;
}

public BinaryNode getRoot() {
return root;
}

public void setRoot(BinaryNode root) {
this.root = root;
}


public int getNumOfNodes(){
return root.getNumOfNodes();
}

public void inOrderTraverse(){

inOrderTraverse(root);
}

//用栈方法遍历
public void inOrderStackTraverse(){

Stack stack=new Stack();
BinaryNode cur=root;
//stack.push(root);
while(!stack.isEmpty()||(cur!=null)){
while(cur!=null)
{

stack.push(cur);
cur=cur.getLeft();


}
if(!stack.isEmpty())
{
BinaryNode tmp=stack.pop();
if(tmp!=null)
{System.out.println(tmp.getData());
cur=tmp.getRight();

}

}
}
}
// 递归遍历
public void inOrderTraverse(BinaryNode node){

if(node!=null)
{inOrderTraverse(node.getLeft());
System.out.println(node.getData());

inOrderTraverse(node.getRight());
}
}

public static void main(String[] args) {
Binarytree t=new Binarytree();
Binarytree t8=new Binarytree("8");
Binarytree t7=new Binarytree("7");
t.setTree("6",t7,t8); //用t7,t8设置树t

t.inOrderStackTraverse();
System.out.println(t.getHeight());
}
}

摘自 嵇康的专栏