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?

/**
 * 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> a;
        postorder(root, a);
        return a;
    }
    void postorder(TreeNode *root, vector<int> &array){
        if(root==NULL) return;
        postorder(root->left, array);
        postorder(root->right, array);
        array.push_back(root->val);
    }
};

 

posted on 2014-12-03 11:42  code#swan  阅读(92)  评论(0)    收藏  举报

导航