码迷,mamicode.com
首页 > 其他好文 > 详细

【leetcode】Binary Tree Postorder Traversal

时间:2015-04-26 19:34:19      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:

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?

 

 1 class Solution {
 2 public:
 3     vector<int> postorderTraversal(TreeNode *root) {
 4         vector<int> out;
 5         stack<TreeNode*> s;
 6         TreeNode* node=root;
 7         s.push(node);
 8         while(!s.empty()&&node){
 9             node=s.top();
10             out.push_back(node->val);
11             s.pop();
12             if(node->left) s.push(node->left);
13             if(node->right) s.push(node->right);
14         }
15         
16         reverse(out.begin(),out.end());
17         return out;
18     }
19 };

 

【leetcode】Binary Tree Postorder Traversal

标签:

原文地址:http://www.cnblogs.com/jawiezhu/p/4458153.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!