数据结构二叉树(三)

2014-11-24 03:02:54 · 作者: · 浏览: 2

* @param node
*/
public void midList2(Node node){
Stack stack = new Stack() ;
while(node != null || !stack.isEmpty()){
if(node != null){
stack.push(node) ;
node = node.getLeftChild() ;
}else{
node = stack.pop() ;
System.out.print(node.getData() + ",");
node = node.getRightChild() ;
}
}
}

/**
* 先序遍历递归算法
* @param node
*/
public void preList(Node node){
if(node != null){
System.out.print(node.getData() + ",");
preList(node.getLeftChild()) ;
preList(node.getRightChild()) ;
}
}

/**
* 线序遍历的非递归实现
* @param node
*/
public void preList2(Node p){
Stack stack = new Stack() ;
while(p != null || !stack.isEmpty()){
if(p != null){
System.out.print(p.getData() + ",") ;//输出节点的值
stack.push(p) ; //把根节点入栈
p = p.getLeftChild() ;//寻找左孩子
}else{
p = stack.pop().getRightChild() ;
}
}
}


public Node getRoot() {
return root;
}


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


public int getCount() {
return count;
}


public void setCount(int count) {
this.count = count;
}
}


这里主要实现了二叉树的先序、中序、后序遍历的递归算法和非递归算法。对二叉树的深度和层次遍历没有实现,希望看了此文章的朋友们可以自己实现!