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

  • 相关阅读:
    【第三章】DI的配置使用(一)
    【第二章】IoC的配置使用(一)
    【第二章】IoC的基础与详解(一)
    【第一章】 Spring概述(二)
    【第一章】 Spring概述(一)
    数据库分库分表思路
    Java的内存模型JVM
    Servlet 单例多线程详细解释
    三极管
    续流二极管
  • 原文地址:https://www.cnblogs.com/hrnn/p/13438469.html
Copyright © 2011-2022 走看看