binary-tree-postorder-traversal

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;
    }
};
    原文作者:美不胜收oo
    原文地址: https://www.jianshu.com/p/df08612edb3b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞