Binary Tree Inorder Traversal
2016-07-22 15:16
246 查看
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?
Subscribe to see which companies asked this question
/**
* 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:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
const TreeNode *p = root;
stack<const TreeNode *> s;
while (!s.empty() || p != nullptr) {
if (p != nullptr) {
s.push(p);
p = p->left;
} else {
p = s.top();
s.pop();
result.push_back(p->val);
p = p->right;
}
}
return result;
}
};
For example:
Given binary tree
[1,null,2,3],
1 \ 2 / 3
return
[1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
Subscribe to see which companies asked this question
/**
* 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:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
const TreeNode *p = root;
stack<const TreeNode *> s;
while (!s.empty() || p != nullptr) {
if (p != nullptr) {
s.push(p);
p = p->left;
} else {
p = s.top();
s.pop();
result.push_back(p->val);
p = p->right;
}
}
return result;
}
};
相关文章推荐
- 【HDU-oj】-1061-Rightmost Digit(快速幂)
- Wordpress入门笔记
- JSONP解决跨域完整例子
- codeforces 698B fix a tree 时间戳
- 安装完 MySQL 后必须调整的 10 项配置
- 3D编程知识--矩阵变换
- 尺寸
- 字符串数组空格的替换
- HTML——简介
- fancybox 是一款优秀的 jquery 弹出层展示插件
- Jquery的同步和异步请求
- app砸壳
- 插入节点
- Java 动态生成jpg图片
- 关于tableview cell之间分割线
- PHP微信支付实例解析
- NFS配置
- 正则表达式在JS中的应用
- sql 递归查询
- HDU 2376 树形dp|树上任意两点距离和的平均值