美文网首页LeetCode刷题
binary-tree-postorder-traversal

binary-tree-postorder-traversal

作者: 美不胜收oo | 来源:发表于2018-12-03 23:29 被阅读0次

    title: binary-tree-postorder-traversal

    描述

    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?

    思路

    前序遍历 根->左->右 变成 根->右->左 结果再reverse一下

    代码

    /**
     * Definition for binary tree
     * 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;
            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;
        }
    };
    

    相关文章

      网友评论

        本文标题:binary-tree-postorder-traversal

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