美文网首页
145. Binary Tree Postorder Trave

145. Binary Tree Postorder Trave

作者: xingzai | 来源:发表于2019-05-15 21:12 被阅读0次

    题目链接
    tag:

    • Hard;

    question:
      Given a binary tree, return the postorder traversal of its nodes' values.

    Example:

    Input: [1,null,2,3]
    1
    \
    2
    /
    3
    Output: [3,2,1]
    Follow up: Recursive solution is trivial, could you do it iteratively?

    思路:
      那么在94. Binary Tree Inorder Traversal 二叉树中序遍历中的解法三也可以改动一下变成后序遍历,代码如下:

    /**
     * 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) {
            vector<int> res;
            stack<TreeNode*> s;
            TreeNode *p = root;
            while (!s.empty() || p) {
                if (p) {
                    s.push(p);
                    res.insert(res.begin(), p->val);
                    p = p->right;
                } else {
                    TreeNode *t = s.top(); s.pop();
                    p = t->left;
                }
            }
            return res;
        }
    };
    

    相关文章

      网友评论

          本文标题:145. Binary Tree Postorder Trave

          本文链接:https://www.haomeiwen.com/subject/azzmaqtx.html