zoukankan      html  css  js  c++  java
  • [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;
        }
    };
  • 相关阅读:
    线性回归模型练习
    《代码整洁之道》读书笔记五
    第八周总结
    第七周总结
    《代码整洁之道》读书笔记四
    《代码整洁之道》读书笔记三
    第六周总结
    《代码整洁之道》读书笔记二
    第五周总结
    HDFS的JavaAPI操作
  • 原文地址:https://www.cnblogs.com/zhangbaochong/p/5475308.html
Copyright © 2011-2022 走看看