zoukankan      html  css  js  c++  java
  • 二叉树系列三:二叉树的遍历(递归方法)

    二叉树的遍历分为前序遍历、中序遍历、后序遍历和层次遍历四种,下面分别进行简要的阐述并用C++实现:

    (1)前序遍历

    前序遍历首先访问结点,然后访问其左右子树,如果使用递归算法,那么具体的实现如下:

     1 template<class T>
     2 void Tree<T>::PreOrder(TreeNode<T>* root)
     3 {
     4     if(root != NULL)
     5     {
     6         cout<<root->data<<endl;
     7         PreOrder(root->leftChild);
     8         PreOrder(root->rightChild);
     9     }
    10 }
    View Code

    (2)中序遍历

    中序遍历首先遍历其左子树,然后访问结点,最后遍历右子树,递归实现如下:

     1 template<class T>
     2 void Tree<T>::MidOrder(TreeNode<T>* root)
     3 {
     4     if(root != NULL)
     5     {
     6         MidOrder(root->leftChild);
     7         cout<<root->data<<endl;
     8         MidOrder(root->rightChild);
     9     }
    10 }
    View Code

    (3)后序遍历

    后续遍历首先遍历结点的左右子树,然后访问结点,递归实现如下:

     1 template<class T>
     2 void Tree<T>::PostOrder(TreeNode<T>* root)
     3 {
     4     if(root != NULL)
     5     {        
     6         PostOrder(root->leftChild);
     7         PostOrder(root->rightChild);
     8         cout<<root->data<<endl;
     9     }
    10 }
    View Code

    (4)层次遍历(非递归)

     此方法中不适用递归方法,而是借助队列,访问当前结点后,将其左右子女(非左右子树)压入队列中,然后弹出队列中的第一个元素,按照同样的方法处理,代码实现如下:

     1 template<class T>
     2 void Tree<T>::LevelOrder(TreeNode<T>* root)
     3 {
     4     if(root != NULL)
     5     {    
     6         queue<TreeNode<T>*> q;
     7         TreeNode<T>* curr = root;
     8         TreeNode<T>* temp = root;
     9         while(curr)
    10         {
    11             cout<<curr->data<<endl;
    12             if(curr->leftChild)
    13                 q.push(curr->leftChild);
    14             if(curr->rightChild)
    15                 q.push(curr->rightChild);
    16             if(!q.empty())
    17             {
    18                 curr = q.front();
    19                 q.pop();
    20             }
    21             else
    22                 curr = NULL;
    23         }
    24     }
    25 }
    View Code
  • 相关阅读:
    全站生成静态文件的通用方法
    Web.config配置文件详解(新手必看)
    iis7/7.5设置上传文件最大大小
    C# 中的常用正则表达式总结
    60款很酷的 jQuery 幻灯片演示和下载
    DataReader记录生成多列的表格
    正则表达式
    博客转移
    ASP.Net学习之常用SQL存储过程(1)
    遍历Request的信息
  • 原文地址:https://www.cnblogs.com/sophia-yun/p/3144213.html
Copyright © 2011-2022 走看看