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

      

  • 相关阅读:
    透视分析
    仪表分析
    sql查询和预览界面,在预览界面选择图表最后进行导出数据和图表到excel
    可视化查询
    创建数据源
    Smartbi使用Oracle RAC数据库做知识库
    反应器(Reactor)模式
    Netty:EventLoopGroup
    ShuffleTest java 使用集合的方式进行排序
    MapTest java 核心编程
  • 原文地址:https://www.cnblogs.com/zqlmmd/p/5397872.html
Copyright © 2011-2022 走看看