zoukankan      html  css  js  c++  java
  • 树的非递归遍历

    树的非递归遍历

     1 void preorderTravel(Tree *T){
     2     if(T==NULL){
     3         return;
     4     }
     5     stack<TreeNode *> S;
     6     s.push(T);
     7     
     8     while(!S.empty()){
     9         TreeNode *p = S.top();
    10         S.pop();
    11         visit(p);
    12         if(p->left){
    13             S.push(p->left);
    14         }
    15         if(p->right){
    16             S.push(p->right);
    17         }
    18     }
    19 }
    20 
    21 void inorderTravel(Tree *T){
    22     if(T==NULL){
    23         return;
    24     }
    25     stack<TreeNode *> S;//准备一个栈 
    26     TreeNode *t = T;//准备一个用来向左扎的指针 
    27     while(!S.empty() || t){
    28         while(t){
    29             S.push(t); 
    30             t=t->left;
    31         }
    32         if(!S.empty()){//扎到头了,弹出来一个 
    33             TreeNode *p = S.top();
    34             S.pop();
    35             visit(p);
    36             t=p->left;//往右 
    37         }
    38     } 
    39 }
    40 
    41 
    42 void postorderTravel(TreeNode *T){
    43     if(T==NULL){
    44         return;
    45     }
    46     stack< pair<TreeNode *, bool> > S;
    47     s.push(make_pair(T, false));
    48     bool isPassed;
    49     while(!S.empty()){
    50         pair<TreeNode *, bool> p = S.top();
    51         S.pop();
    52         isPassed = p.second;
    53         if(isPassed){
    54             visit(p.first);
    55         }else{
    56             s.push(make_pair(p.first, true));
    57             if((p.first)->left){
    58                 s.push(make_pair((p.first)->left, false));
    59             }
    60             if((p.first)->right){
    61                 s.push(make_pair((p.first)->right, false));
    62             }
    63         }
    64     }
    65 } 
  • 相关阅读:
    php的语句
    php
    git分支
    git安装及git命令的用法
    git命令
    dos命令及github介绍
    无缝轮播的案例 及css3无缝轮播案例
    ACWING 031 表示数值的字符串
    Acwing 282. 石子合并 区间dp
    Leetcode 841. 钥匙和房间 dfs bfs
  • 原文地址:https://www.cnblogs.com/zhishoumuguinian/p/12051893.html
Copyright © 2011-2022 走看看