zoukankan      html  css  js  c++  java
  • leetcode6:binary-tree-postorder-traversal

    题目描述

    求给定的二叉树的后序遍历。
    例如:
    给定的二叉树为{1,#,2,3},
       1↵    ↵     2↵    /↵   3↵
    返回[3,2,1].
    备注;用递归来解这道题太没有新意了,可以给出迭代的解法么?


    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?


    示例1

    输入

    复制
    {1,#,2,3}

    输出

    复制
    [3,2,1]
    
    /**
     * struct TreeNode {
     *    int val;
     *    struct TreeNode *left;
     *    struct TreeNode *right;
     * };
     */

    class Solution {
    public:
        /**
         *
         * @param root TreeNode类
         * @return int整型vector
         */
        vector<int> postorderTraversal(TreeNode* root) {
            // write code here
            vector <int> res;
            if (!root)
                return res;
            stack<TreeNode *> st;
            st.push(root);
            while (st.size())
            {
                TreeNode *temp=st.top();
                st.pop();
                res.push_back(temp->val);
                if (temp->left)
                    st.push(temp->left);
                if (temp->right)
                    st.push(temp->right);
            }
            reverse (res.begin(),res.end());
            return res;
        }
    };

  • 相关阅读:
    scala简单的功能实现~weektwo
    linux中/dev/null与2>&1讲解
    scala简单的功能实现~weekone
    oracle之随机数
    oracle之percent_rank() over()函数和PERCENTILE_CONT() within group()over()函数详解
    awk编程的基本用法
    Django-路由系统
    selectors模块
    threading中定时器Timer方法
    HTML-W3school首页制作
  • 原文地址:https://www.cnblogs.com/hrnn/p/13438469.html
Copyright © 2011-2022 走看看