1. 程式人生 > >title: 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; } };