二叉树递归和非递归遍历 (二)

2014-11-24 10:46:21 · 作者: · 浏览: 16
ent node
//step2:visit current node
//step3:push current's right child
//step4:push current's left child
//step5: loop step1-step5

privete void pushPreOrderNode(Node current, Stack s){
if(current==null)
return ;
if(!s.empty()){
leftChild=current.leftChild;
rightChild=curret.rightChild;

if(rightChild!=null) //push rightChild
s.push(rightChild);
if(leftChild!=null) //push leftChild
s.push(leftChild):
visit(current); //current always first visit in preOrder
}//end if
}//end pushPreOrderNode()

public void preOrder(Node root){
//special case
if(root==null)
return ;

//inintial current node
Node current=root;
//inintial stack
Stack s=new Stack();
pushPreOrderNode(current,s);

//base case:stack is empty
while( !s.empty() ){
//pop
current=s.pop();
//push
pushPreOrderNode(current,s);
}//end while
}//end preOrder()

// 中序遍历(非递归实现)-------------------------------------------------------------
/*
left current right
*/

public void inOrder( Node root){
//special case
if(root==null)
return;

Node current=root;
//initial stack
Stack s=new Stack();
pushInOrderNode(current,s);

//pop and visit
while( !s.empty() ){
current=s.pop();
if(current.bPushed)
visit(current);
else
pushInOrderNode(current,s);
}//end while
}//end postOrder()

private void pushInOrderNode(Node current,Stack s){
if(current==null)
return;
if(!s.empty()){
leftChild=current.leftChild;
rightChild=curret.rightChild;

if(rightChild!=null){ //push rightChild
s.push(rightChild);
rightChild.bPushed=false;
}//end if

s.push(current); //push current



if(leftChild!=null){ //push leftChild
s.push(leftChild);
rightChild.bPushed=false;
}//end if

//set flag, ture present current's left and right has both pushed
current.bPushed=true;
}//end if
}//end if
}//end pushInOrderNode()
// -------------------------------------------------------------


// 后序遍历(递归实现)-------------------------------------------------------------
/*
left right current
step1:初始化栈
按照step2初始化栈
step2:入栈
入栈顺序:current,right,left
如果current的中左右节点都入栈了,将current标识为true;
将入栈的左右节点标识初始化为false
step3:出栈
出栈节点设置为current,
如果current标识为ture,访问之;如果为false,做step2步骤
step4:重复step2&step3
*/

public void postOrder( Node root){
//special case
if(root==null)
return;

Node current=root;

//initial stack
Stack s=new Stack();
pushPostOrderNode(current,s);

//pop and visit
while( !s.empty() ){
current=s.pop();
if(current.bPushed)
visit(current);
else
pushPostOrderNode(current,s);
}//end while
}//end postOrder()

// 左右子树尚未入栈,则依次将 根节点,右节点,左节点 入栈
private void pushPostOrderNode(Node current, Stack s){
if(current==null)
return;
if(!s.empty()){