• [LeetCode145]Binary Tree Postorder Traversal


    题目:

    Given a list, rotate the list to the right by k places, where k is non-negative.

    For example:
    Given 1->2->3->4->5->NULL and k = 2,
    return 4->5->1->2->3->NULL.

    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?

    分类:Tree Stack

    代码:二叉树非递归后序遍历

    /**
     * Definition for a binary tree node.
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        vector<int> postorderTraversal(TreeNode* root) {
            stack<TreeNode*> s;
            vector<int> nodes;
            TreeNode* cur = root;//u当前访问的结点
            TreeNode* lastNode = NULL;//上次访问的结点 
            while(cur || !s.empty())
            {
                //一直向左走直到为空为止
                while(cur)
                {
                    s.push(cur);
                    cur = cur->left;
                }
                cur = s.top();
                //如果结点右子树为空或已经访问过,访问当前结点
                if(cur->right == NULL || cur->right == lastNode)
                {
                    nodes.push_back(cur->val);
                    lastNode = cur;
                    s.pop();
                    cur = NULL;
                }
                else
                    cur = cur->right;
            }
            return nodes;
        }
    };
  • 相关阅读:
    HBase 安装设置
    Python中通过函数对象创建全局变量
    Scala 中 构造函数,重载函数的执行顺序
    Hive 安装配置
    976. 三角形的最大周长
    922. 按奇偶排序数组 II
    350. 两个数组的交集 II
    349. 两个数组的交集
    242. 有效的字母异位词
    925. 长按键入
  • 原文地址:https://www.cnblogs.com/zhangbaochong/p/5475308.html
Copyright © 2020-2023  润新知