zoukankan      html  css  js  c++  java
  • [LeetCode] Binary Tree Postorder Traversal

    Given a binary tree, return the postorder traversal of its nodes' values.

    For example:
    Given binary tree {1,#,2,3},

       1
        
         2
        /
       3
    

    return [3,2,1].

    Note: Recursive solution is trivial, could you do it iteratively?

    思路: 用r表示最近访问过的节点。

       时间复杂度O(n), 空间复杂度O(n)

     1 /**
     2  * Definition for binary tree
     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 public:
    12     vector<int> postorderTraversal(TreeNode *root) {
    13         vector<int> result;
    14         stack<TreeNode *> s;
    15         TreeNode *p = root, *r = NULL;
    16         
    17         while (p != NULL || !s.empty()) {
    18             if (p!= NULL) {
    19                 s.push(p);
    20                 p = p->left;
    21             } else {
    22                 p = s.top();
    23                 if (p->right != NULL && p->right != r) {
    24                     p = p->right;
    25                 } else {
    26                     result.push_back(p->val);
    27                     s.pop();
    28                     r = p;
    29                     p = NULL;
    30                 }
    31             }
    32         }
    33         
    34         return result;
    35     }
    36 };
  • 相关阅读:
    [洛谷P2463][SDOI2008]Sandy的卡片
    后缀数组
    周记【距gdoi:110天】
    hdu3068最长回文(Manacher算法)
    二分图的一些题目合集
    周记【距gdoi:117天】
    二分图、网络流模版总结
    2014end
    周记【距gdoi:126天】
    2-sat
  • 原文地址:https://www.cnblogs.com/vincently/p/4229660.html
Copyright © 2011-2022 走看看