首页 > 其他 > 详细

Leetcode #94 Binary Tree Inorder Traversal

时间:2015-04-05 23:28:21      阅读:271      评论:0      收藏:0      [点我收藏+]

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

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

 1 class Solution
 2 {
 3 public:
 4     vector<int> inorderTraversal(TreeNode *root)
 5     {
 6         vector<int> output;
 7         if(root == NULL)
 8         {
 9             return output;
10         }
11 
12         stack<TreeNode*> nodeStack;
13 
14         while(root != NULL || !nodeStack.empty())
15         {
16             if(root != NULL)
17             {
18                 nodeStack.push(root);
19                 root = root->left; //找到最左边的叶子节点。
20             }
21             else
22             {
23                 root = nodeStack.top(); //回退一个节点。
24                 nodeStack.pop();
25                 output.push_back(root->val); //输出当前节点。
26                 root = root->right; //进入右子树。当前节点并没有再次入栈,也就是说,下次回退的时候,会退到当前节点的父节点,从而避免了重复打印。
27             }
28         }
29 
30         return output;
31     }
32 };

 

Leetcode #94 Binary Tree Inorder Traversal

原文:http://www.cnblogs.com/meowcherry/p/4394889.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!