zoukankan      html  css  js  c++  java
  • Binary Tree Iterative Traversal

    Preorder

     1 class Solution {
     2 public:
     3     vector<int> preorderTraversal(TreeNode* root) {
     4         vector<int> res;
     5         if (!root) return res;
     6         stack<TreeNode *> sta;
     7         sta.push(root);
     8         while (!sta.empty())
     9         {
    10             TreeNode* cur = sta.top();
    11             sta.pop();
    12             res.push_back(cur->val);
    13             if (cur->right) sta.push(cur->right);
    14             if (cur->left) sta.push(cur->left);
    15         }
    16         return res;
    17     }
    18 };

    postorder

     1 class Solution {
     2 public:
     3     vector<int> postorderTraversal(TreeNode* root) {
     4         vector<int> res;
     5         if (!root) return res;
     6         stack<TreeNode *> sta;
     7         sta.push(root);
     8         TreeNode *last = NULL;
     9         while (!sta.empty())
    10         {
    11             TreeNode *cur = sta.top();
    12             TreeNode *left = cur->left, *right = cur->right;
    13             if (left && (!last || (last != left && last != right)))
    14                 sta.push(left);
    15             else if (right && (!last || last != right))
    16                 sta.push(right);
    17             else
    18             {
    19                 res.push_back(cur->val);
    20                 last = cur;
    21                 sta.pop();
    22             }
    23         }
    24         return res;
    25     }
    26 };

    inorder

     1 class Solution {
     2 public:
     3     vector<int> inorderTraversal(TreeNode* root) {
     4         vector<int> res;
     5         stack<TreeNode*> sta;
     6         while(1) {
     7             while(root) { sta.push(root); root = root->left; }
     8             if(sta.empty()) break;
     9             root = sta.top(); sta.pop();
    10             res.push_back(root->val);
    11             root = root->right;
    12         }
    13         return res;
    14     }
    15 };

      

  • 相关阅读:
    illegal line end in String Iiteral错误
    mavem的tomcat插件热加载
    解决IntelliJ IDEA启动缓慢
    进行JDBC连接时增加以下代码:
    基于Reflect将List泛型数据源转换为Json字符串
    数据库还原至指定时间节点
    EF关系配置之N:N关系
    EF关系配置之1:N
    EF+Lambda查询性能测试
    EntityFramework基础框架搭建
  • 原文地址:https://www.cnblogs.com/fenshen371/p/5168073.html
Copyright © 2011-2022 走看看