首页 > 其他 > 详细

【leetcode】Binary Tree Postorder Traversal

时间:2015-04-26 19:31:17      阅读:215      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!