LeetCode之Binary Tree Inorder Traversal
2015-08-05 15:59
399 查看
/*方法一:递归中序遍历。*/ class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> res; inorder(root, res); return res; } void inorder(TreeNode* root, vector<int> &res){ if(root == nullptr) return; if(root->left != nullptr) inorder(root->left, res); res.push_back(root->val); if(root->right != nullptr) inorder(root->right, res); } }; /*方法二:利用栈,迭代法中序遍历*/ class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> res; if(root == nullptr) return res; stack<TreeNode*> s; TreeNode *p = root; while(!s.empty() || p != nullptr){ if(p != nullptr){ s.push(p); p = p->left; } else{ p = s.top(); s.pop(); res.push_back(p->val); p = p->right; } } return res; } };
相关文章推荐
- 使用php-java-bridge让PHP5支持java
- C#高级编程七十一天----DLR ScriptRuntime
- Hadoop集群(第9期)_MapReduce初级案例
- android 自定义ScrollView实现背景图片伸缩(阻尼效果)
- ListView,图片,两行内容
- opentsdb
- 程序人生成长发展中的一些感悟
- 关于相对路径
- C# 调用 C++ 写的Dll 遇到的问题(调用DLL 自动退出)
- go项目make
- Windows API CreateEvent函数用法
- eclipse+ EPIC + PadWalker 搭建Windows Perl开发环境
- 判断app是在前台还是后台
- Python中eval带来的潜在风险
- HBase简介(很好的梳理资料)
- css 画基本图形
- 按钮,alert,EditText
- 关于std::map
- php 遍历一个文件夹下面的子文件
- Rescue(BFS) HDU 1242