[leetcode] 145. Binary Tree Postorder Traversal 解题报告

题目链接:https://leetcode.com/problems/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?


思路:递归的比较简单。迭代的想了好久没想到怎么做,后来看到居然是按照先序的思路,左右子树入栈顺序相反,最后将得到后序相反的序列,然后将这个序列翻转一下就可以了,感觉这种做法也挺意外的。180题了,很快就到200题的关卡了得意

两种代码如下:

递归:

/**
 * 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) {
        if(!root) return result;
        postorderTraversal(root->left);
        postorderTraversal(root->right);
        result.push_back(root->val);
        return result;
    }
private:
    vector<int> result;
};


迭代:

/**
 * 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) {
        if(!root) return result;
        st.push(root);
        while(!st.empty())
        {
            TreeNode* tem = st.top();
            st.pop();
            result.push_back(tem->val);
            if(tem->left) st.push(tem->left);
            if(tem->right) st.push(tem->right);
        }
        reverse(result.begin(), result.end());
        return result;
    }
private:
    stack<TreeNode*> st;
    vector<int> result;
};
第二种方法参考:https://leetcode.com/discuss/66062/c-iterative-solution-0ms-with-a-stack

你可能感兴趣的:(LeetCode,tree,binary)