zoukankan      html  css  js  c++  java
  • 【面经】用递归方法对二叉树进行层次遍历 && 二叉树深度

     1 void PrintNodeAtLevel(BiTree T,int level)
     2   {
     3      // 空树或层级不合理
     4       if (NULL == T || level < 1 )
     5           return;
     6   
     7       if (1 == level)
     8       {
     9           cout << T->data << "  ";
    10          return;
    11      }
    12  
    13      // 左子树的 level - 1 级
    14      PrintNodeAtLevel(T->leftChild,  level - 1);
    15  
    16      // 右子树的 level - 1 级
    17      PrintNodeAtLevel(T->rightChild, level - 1);
    18  }
    19  
    20  
    21  void LevelTraverse(BiTree T)
    22  {
    23      if (NULL == T)
    24          return;
    25  
    26      int depth = Depth(T);
    27  
    28      int i;
    29      for (i = 1; i <= depth; i++)
    30      {
    31          PrintNodeAtLevel(T, i);
    32          cout << endl;
    33      }
    34  }

    二叉树的深度,递归和非递归实现

    递归实现基本思想:

    为了求得树的深度,可以先求左右子树的深度,取二者较大者加1即是树的深度,递归返回的条件是若节点为空,返回0

    算法:

    复制代码
    1 int FindTreeDeep(BinTree BT){
    2      int deep=0;
    3      if(BT){
    4          int lchilddeep=FindTreeDeep(BT->lchild);
    5          int rchilddeep=FindTreeDeep(BT->rchild);
    6          deep=lchilddeep>=rchilddeep?lchilddeep+1:rchilddeep+1;
    7      }
    8      return deep;
    9 }
    复制代码

    非递归实现基本思想:

    受后续遍历二叉树思想的启发,想到可以利用后续遍历的方法来求二叉树的深度,在每一次输出的地方替换成算栈S的大小,遍历结束后最大的栈S长度即是栈的深度。

    算法的执行步骤如下:

    (1)当树非空时,将指针p指向根节点,p为当前节点指针。

    (2)将p压入栈S中,0压入栈tag中,并令p执行其左孩子。

    (3)重复步骤(2),直到p为空。

    (4)如果tag栈中的栈顶元素为1,跳至步骤(6)。从右子树返回

    (5)如果tag栈中的栈顶元素为0,跳至步骤(7)。从左子树返回

    (6)比较treedeep与栈的深度,取较大的赋给treedeep,对栈S和栈tag出栈操作,p指向NULL,并跳至步骤(8)。

    (7)将p指向栈S栈顶元素的右孩子,弹出栈tag,并把1压入栈tag。(另外一种方法,直接修改栈tag栈顶的值为1也可以)

    (8)循环(2)~(7),直到栈为空并且p为空

    (9)返回treedeep,结束遍历

    复制代码
     1 int TreeDeep(BinTree BT ){
     2     int treedeep=0;
     3     stack S;
     4     stack tag;
     5     BinTree p=BT;
     6     while(p!=NULL||!isEmpty(S)){
     7         while(p!=NULL){
     8             push(S,p);
     9             push(tag,0);
    10             p=p->lchild;
    11         }
    12         if(Top(tag)==1){
    13             deeptree=deeptree>S.length?deeptree:S.length;
    14             pop(S);
    15             pop(tag);
    16             p=NULL;
    17         }else{
    18             p=Top(S);
    19             p=p->rchild;
    20             pop(tag);
    21             push(tag,1);
    22         }
    23     }
    24     return deeptree;
    25 }
    复制代码
  • 相关阅读:
    JavaScript操作符instanceof揭秘
    Linux打开txt文件乱码的解决方法
    Working copy locked run svn cleanup not work
    poj 2299 UltraQuickSort 归并排序求解逆序对
    poj 2312 Battle City 优先队列+bfs 或 记忆化广搜
    poj2352 stars 树状数组
    poj 2286 The Rotation Game 迭代加深
    hdu 1800 Flying to the Mars
    poj 3038 Children of the Candy Corn bfs dfs
    hdu 1983 Kaitou Kid The Phantom Thief (2) DFS + BFS
  • 原文地址:https://www.cnblogs.com/QoQian/p/5438278.html
Copyright © 2011-2022 走看看