• 【Leetcode】145. 二叉树的后序遍历


    45. 二叉树的后序遍历

    后续遍历顺序:

    • 后序遍历其左子树;
    • 后序遍历其右子树;
    • 访问根结点。

    解法1:

     1 /**
     2 * Definition for a binary tree node.
     3 * struct TreeNode {
     4 *     int val;
     5 *     TreeNode *left;
     6 *     TreeNode *right;
     7 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     8 * };
     9 */
    10 class Solution
    11 {
    12 public:
    13     vector<int> postorderTraversal(TreeNode* root)
    14     {
    15         vector<int> nums;
    16 
    17         if (!root)
    18             return nums;
    19 
    20         stack<TreeNode*> s;
    21         TreeNode *p;
    22         s.push(root);
    23         p = root->left;
    24 
    25         while (!s.empty())
    26         {
    27             while (p != nullptr)
    28             {
    29                 s.push(p);
    30                 p = p->left;
    31             }
    32 
    33             bool flag = true;
    34             p = nullptr;
    35 
    36             while (!s.empty() && flag)
    37             {
    38                 root = s.top();
    39                 if (root->right == p)
    40                 {
    41                     s.pop();
    42                     nums.push_back(root->val);
    43                     p = root;
    44                 }
    45                 else
    46                 {
    47                     flag = false;
    48                     p = root->right;
    49                 }
    50             }
    51         }
    52         return nums;
    53     }
    54 };


     

  • 相关阅读:
    PHP中关于字符串的连接
    好用的FireFox(FF)插件
    Scripted Operation
    Scripted device
    chgrp chown
    wait_for_devices
    mysql create user
    mysql
    create user mysql
    Inserting/Removing shutters and filters
  • 原文地址:https://www.cnblogs.com/sunbines/p/15535755.html
Copyright © 2020-2023  润新知