Leetcode Binary Tree Inorder Traversal
2024-10-18 18:30:41
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;
}
};
非递归中序遍历
最新文章
- day26_网络编程第一天
- 频域分辨率与DFT,DCT,MDCT理解
- linux下python版webshell后门查杀工具
- HTMl中Meta标签详解以及meta property=og标签含义
- 字体图标 icon font
- sql查阅每一月的数据
- html p标签换行问题
- centos6安装vncserver实现图形化访问
- Objective-C继承
- PAT 天梯赛 L2-007 家庭房产
- Sicily 1151 魔板
- SQL Server安装【转载】
- C#学习笔记之值类型与引用类型
- 在 vue.js 中动态绑定 v-model
- web 前端安全问题
- 关于javascript三目
- Spring MVC 学习笔记8 —— 实现简单的用户管理(4)用户登录
- Linux ulimit
- hive 安装记录
- C++易混淆知识点整理