[LeetCode] 94 - Binary Tree Inorder Traversal
2015-10-03 10:49
417 查看
Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree
return
Note: Recursive solution is trivial, could you do it iteratively?
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
#if 0
void doInorder(TreeNode *node, vector<int> &res) {
if (node->left) doInorder(node->left, res);
res.push_back(node->val);
if (node->right) doInorder(node->right, res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if (!root) return res;
doInorder(root, res);
return res;
}
#else
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if (!root) return res;
stack<TreeNode* > treeStack;
do {
while (root) {
treeStack.push(root);
root = root->left;
}
if (!treeStack.empty()) {
root = treeStack.top();
treeStack.pop();
res.push_back(root->val);
root = root->right;
}
} while(root || !treeStack.empty());
return res;
}
#endif
};
For example:
Given binary tree
{1,#,2,3},
1 \ 2 / 3
return
[1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
#if 0
void doInorder(TreeNode *node, vector<int> &res) {
if (node->left) doInorder(node->left, res);
res.push_back(node->val);
if (node->right) doInorder(node->right, res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if (!root) return res;
doInorder(root, res);
return res;
}
#else
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if (!root) return res;
stack<TreeNode* > treeStack;
do {
while (root) {
treeStack.push(root);
root = root->left;
}
if (!treeStack.empty()) {
root = treeStack.top();
treeStack.pop();
res.push_back(root->val);
root = root->right;
}
} while(root || !treeStack.empty());
return res;
}
#endif
};
相关文章推荐
- 使用Hive整合Hbase
- java篇 【13】java怎样去开发一个程序呢
- 连接池1
- 常用 shell 脚本
- Reorder List
- DNS原理及其解析过程
- PHP递归打印
- android下载的进度条
- android TabHost制作底部导航栏
- Java闭包简析
- AdapterViewFlipper实现图片自动播放功能
- 数据库中DDL、DML、DCL和TCP概念
- CentOS6.5设备MRBS
- 昨天发现的nginx默认不支持下划线引起angular-phonecat项目部分文件404问题
- 1.3.4 为在保护模式下执行head.s做准备
- ASF(传感器)
- Linux 守护进程的编程方法 http://blog.csdn.net/hairetz/article/details/4195036
- java 网络编程——day23
- socket编程
- OC学习笔记之Foundation框架NSNumber、NSValue和NSDate(转)