# Binary Tree Postorder Traversal

Problem:

Given a binary tree, return the postorder traversal of its nodes' values.

For example:

Given binary tree {1, #, 2, 3},

return [3, 2, 1]

Note: Recursive solution is trivial, could you do it iteratively?

 1 class Solution {
2 public:
3     vector<int> postorderTraversal(TreeNode *root) {
4         vector<int> result;
5         stack<TreeNode *> stk;
6         TreeNode *p = root;
7         while(p != NULL) {
8             stk.push(p);
9             p = p->left;
10         }
11
12         while(!stk.empty()) {
13             TreeNode *top = stk.top();
14             if(top->right == NULL || result.size() > 0 && top->right->val == result.back()) {
15                 result.push_back(top->val);
16                 stk.pop();
17             } else {
18                 TreeNode *p = top->right;
19                 while(p != NULL) {
20                     stk.push(p);
21                     p = p->left;
22                 }
23             }
24         }
25         return result;
26     }
27 };

posted @ 2014-04-28 21:44  夏目家的猫咪老师  阅读(122)  评论(0编辑  收藏  举报