zoukankan      html  css  js  c++  java
  • 二叉树的遍历--递归及非递归实现

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

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

    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);
       }
       
    }
    

      

  • 相关阅读:
    small case change m and n
    关于闭包
    如何让IE兼容css3属性?
    全屏滚动插件
    bind()&call()&apply()的区别?
    nodejs和npm的关系
    数据库面试题整理
    微机原理复习整理
    软件工程复习整理
    leetcode字符串系列
  • 原文地址:https://www.cnblogs.com/zqlmmd/p/5397872.html
Copyright © 2011-2022 走看看