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;
        }
    };

  • 相关阅读:
    BZOJ(2) 1041: [HAOI2008]圆上的整点
    BZOJ(1) 1003 [ZJOI2006]物流运输
    HDU 1285 确定比赛名次
    洛谷 P2951 [USACO09OPEN]捉迷藏Hide and Seek
    POJ 1201 Intervals
    2017 软件工程 个人作业——软件产品案例分析
    2017 软件工程 个人技术博客(α)
    在VS2017上对C++项目进行单元测试
    ASC47B borderless
    ASC47B borderless
  • 原文地址:https://www.cnblogs.com/hrnn/p/13438469.html
Copyright © 2011-2022 走看看