二叉树的遍历

遍历二叉树的三种方法:

前序:根节点->左子树->右子树

中序:左子树->根节点->右子树

后序:左子树->右子树->根节点

前序遍历的递归算法:

public void preOrderRecursion(BinaryTreeNode root,List list){

if(root==null) return ;
list.insertLast(root);
preOrderRecursion(root.getLChild(),list);
preOrderRecursion(root.getRChild(),list);
}

 

中序遍历的递归算法:

public void inOrderRecursion(BinaryTreeNode root,List list){

if(root==null) return ;
inOrderRecursion(root.getLChild(),list);
list.insertLast(root);
inOrderRecursion(root.getRChild(),list);
}

 

后序遍历的递归算法:

public void postOrderRecursion(BinaryTreeNode root,List list){

if(root==null) return ;

postOrderRecursion(root.getLChild(),list);
postOrderRecursion(root.getRChild(),list);
list.insertLast(root);
}

 

前序遍历的非递归算法:

public void preOrderTraverse(BinaryTreeNode root,List list){
if(root==null)return;
Stack s=new Stack();//堆栈
while(root!=null){
   while(root!=null){
       list.insertLast(root);
       if(root.getRChild()!=null)s.push(root.getRhild());
       root=root.getLChild();
   }
   if(!s.isEmpty()) root=(BinaryTreeNode)s.pop();
}
}

 

中序遍历的非递归算法:

public void inOrderTraverse(BinaryTreeNode root,List list){
if(root==null)return;
Stack s=new Stack();//堆栈
while(root!=null||!s.isEmpty()){
   while(root!=null){
       s.push(root);
       root=root.getLChild();
   }
   if(!s.isEmpty()) {
      root=(BinaryTreeNode)s.pop();
      list.insertLast(root);
      root=root.getRChild();
}
}
}

 

后序遍历的非递归算法:

public void postOrderTraverse(BinaryTreeNode root,List list){
if(root==null)return;
Stack s=new Stack();//堆栈
while(root!=null||!s.isEmpty()){
   while(root!=null){
       s.push(root);
       if(root.getLChild()!=null)root=root.getRhild();
       else root=root.getRChild();
   }
   if(!s.isEmpty()) {
         root=(BinaryTreeNode)s.pop();
         list.insertLast(root);
}
   while(!s.isEmpty()&&((BinaryTreeNode)s.peek()).getRChild()==root){
       root=s.pop();
       list.insertLast(root);
}
   if(!s.isEmpty())
       root=((BinaryTreeNode)s.peek()).getRChild();
   else p=null;
}
}

 

posted on 2014-03-11 11:07  hadoop-yang  阅读(174)  评论(0)    收藏  举报