二叉树的遍历--递归及非递归实现

二叉树的遍历分为前序,中序和后序遍历,层序遍历与深度遍历方法也很重要。

在这里,深度遍历方法用到了栈这种数据结构,广度遍历方法用到了队列这种数据结构。

1.二叉树的链式存储

1 typedef char datatype;
2 
3 typedef struct BinNode{
4          datatype data;
5          struct BinNode* lchild;
6          struct BinNode* rchild;
7 }BinNode;
8 
9 typedef BinNode* bintree;

2.遍历的实现--递归实现

 1 //前序遍历
 2 void preorder(bintree t){
 3   if(t){
 4     printf("%c",t->data);
 5     if(t->lchild) preorder(t->lchild);
 6     if(t->rchild) preorder(t->rchild);
 7  }
 8 }
 9 //中序遍历
10 void midorder(bintree t){
11   if(t){
12      if(t->lchild) midorder(t->lchild);
13      printf("%c",t->data);
14      if(t->rchild) preorder(t->rchild);
15 }
16 }

3.遍历的实现--非递归实现

 

//二叉树深度优先遍历,是使用栈结构 ;   广度优先搜索类似,实用的是队列结构
public void depthOrderedTravel(){
    if(root==null){
      System.out.print("二叉树为空");
      return 0;
   }
    ArrayDeque<treeNode> stack = new ArrayDeque<treeNode>();
    stack.push(root);
    while(stack.imEmpty()==false){
     treeNode node = stack.pop();
     System.out.print(node.value+" ");
     if(node.right!=null)
            stack.push(node.left);
     if(node.left!=null)
            stack.push(node.right);
   }
   
}

  

posted @ 2016-05-08 09:12  zqlmmd  阅读(201)  评论(0编辑  收藏  举报