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

leetcode 145. Binary Tree Postorder Traversal

时间:2015-01-18 13:02:59      阅读:166      评论: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].

 

 1 vector<int> postorderTraversal(TreeNode *root) 
 2     {
 3         vector<int> tree_nodes;
 4         stack<TreeNode*> stree;
 5         TreeNode* visit = root, *peek = NULL, *last_visit = NULL;
 6         
 7         while (!stree.empty() || (visit != NULL))
 8         {
 9             if (visit != NULL)
10             {
11                 stree.push(visit);
12                 visit = visit->left;
13             }
14             else
15             {
16                 peek = stree.top();   
17                 if ((peek->right != last_visit) && (peek->right != NULL))
18                 {
19                     visit = peek->right;
20                 }
21                 else
22                 {
23                     tree_nodes.push_back(peek->val);
24                     last_visit = peek;
25                     stree.pop();
26                 }
27             }
28         }
29         
30         return tree_nodes;
31     }

 

leetcode 145. Binary Tree Postorder Traversal

标签:

原文地址:http://www.cnblogs.com/ym65536/p/4231614.html

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