• [存档] 非递归后根遍历二叉树



     1 void NonRecursive_PostOrderTraversal(TreeNode *root){
     2     if(!root){
     3         cout<<"Empty tree"<<'\n';
     4         return;
     5     }
     6     stack<TreeNode *> s;
     7     TreeNode *cur = root;
     8     TreeNode *prev = root;
     9     s.push(root);
    10     while(!s.empty()){
    11         if(cur->Left && prev != cur->Left && prev != cur->Right){
    12                 s.push(cur->Left); 
    13                 prev = cur; 
    14                 cur = cur->Left;
    15                 continue//如果有左子树且从未访问过,先访问左子树
    16         }
    17         if(cur->Right && prev !=cur->Right){
    18             s.push(cur->Right); 
    19             prev = cur; 
    20             cur = cur->Right;
    21         }else{
    22             cout<<cur->Value<<"";
    23             prev = cur; 
    24             s.pop(); 
    25             if(!s.empty()){
    26                 cur = s.top(); 
    27             }
    28         }
    29     }
    30     cout<<"end"<<'\n';
    31 }
  • 相关阅读:
    UEFI Protocol
    MFC使用自定义资源加载PNG
    C/C++中的static关键字详解
    spring boot 日志配置 默认的日志配置
    Profile 多环境支持
    YAML语法
    nginx 启动出现 [error] open() "/usr/local/nginx/logs/nginx.pid" failed (2: No such file or directory)
    Nginx日志切割
    Linux 系统安装Nginx
    spring boot Lombok使用方法
  • 原文地址:https://www.cnblogs.com/k330/p/Cpp_NonRecursive_BinTree_PostOrderTraversal.html
Copyright © 2020-2023  润新知