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

Leetcode #145 Binary Tree Postorder Traversal

时间:2015-04-05 23:24:15      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:https://leetcode.com/problems/binary-tree-postorder-traversal/

(非递归实现)二叉树的后序遍历。

 1 class Solution
 2 {
 3 public:
 4     vector<int> postorderTraversal(TreeNode *root)
 5     {
 6         vector<int> output;
 7         if(root == NULL)
 8         {
 9             return output;
10         }
11 
12         stack<TreeNode*> nodeStack;
13         TreeNode *recentlyVisited = NULL;
14 
15         while(root != NULL || !nodeStack.empty())
16         {
17             if(root != NULL)
18             {
19                 nodeStack.push(root);
20                 root = root->left; //找到最左边的叶子节点。
21             }
22             else //左子树为空。
23             {
24                 root = nodeStack.top(); //回退一个节点。
25                 if(root->right != NULL && root->right != recentlyVisited) //右子树不为空并且未访问过。
26                 {
27                     root = root->right;
28                     nodeStack.push(root);
29                     root = root->left;
30                 }
31                 else //右子树为空或者已访问过。
32                 {
33                     root = nodeStack.top(); //回退一个节点。
34                     nodeStack.pop(); //从栈中删除该节点(刚才只回退过,没有删除)。
35                     output.push_back(root->val); //输出该节点。
36                     recentlyVisited = root; //记录下右子树的访问情况(记录的过程是从下至上的)。
37                     root = NULL; //左右子树输出完毕,重置这个节点,在下次进入循环的时候会分配给它栈顶的节点。
38                 }
39             }
40         }
41 
42         return output;
43     }
44 };

 

Leetcode #145 Binary Tree Postorder Traversal

标签:

原文地址:http://www.cnblogs.com/meowcherry/p/4394895.html

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