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

原文地址:https://www.cnblogs.com/hrnn/p/13438469.html