Given a binary tree, return the inorder traversal of its nodes' values.

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?

confused what "{1,#,2,3}" means?

递归解决方案

class Solution {
public:
vector<int> res; void inorder(TreeNode* root){
if(root == NULL) return;
inorder(root->left);
res.push_back(root->val);
inorder(root->right);
} vector<int> inorderTraversal(TreeNode *root) {
inorder(root);
return res;
}
};

递归中序遍历

非递归解决方案

class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> res;
if(root == NULL) return res;
stack<TreeNode *> nodeStack;
TreeNode *current = root;
while(!nodeStack.empty() || current ){
if(current != NULL){
nodeStack.push(current);
current = current->left;
}else{
current = nodeStack.top();nodeStack.pop();
res.push_back(current->val);
current = current->right;
}
}
return res;
}
};

非递归中序遍历

最新文章

  1. day26_网络编程第一天
  2. 频域分辨率与DFT,DCT,MDCT理解
  3. linux下python版webshell后门查杀工具
  4. HTMl中Meta标签详解以及meta property=og标签含义
  5. 字体图标 icon font
  6. sql查阅每一月的数据
  7. html p标签换行问题
  8. centos6安装vncserver实现图形化访问
  9. Objective-C继承
  10. PAT 天梯赛 L2-007 家庭房产
  11. Sicily 1151 魔板
  12. SQL Server安装【转载】
  13. C#学习笔记之值类型与引用类型
  14. 在 vue.js 中动态绑定 v-model
  15. web 前端安全问题
  16. 关于javascript三目
  17. Spring MVC 学习笔记8 —— 实现简单的用户管理(4)用户登录
  18. Linux ulimit
  19. hive 安装记录
  20. C++易混淆知识点整理

热门文章

  1. windows 下的tcping 小插件
  2. 《CLR via C#》读书笔记(5)基元类型、引用类型和值类型
  3. javascript - 浏览器对象
  4. MongoDB增删查改
  5. Arch Linux Installation Guide
  6. sdut 2125串结构练习--字符串匹配【两种KMP算法】
  7. rhel7初体验
  8. [LeetCode] Binary Tree Preorder Traversal
  9. CXF学习(4) 处理无法自动转换的复合数据类型
  10. &lt;转&gt; jsp:include 乱码问题解决