当前位置:网站首页>94. 二叉树的中序遍历(Easy)
94. 二叉树的中序遍历(Easy)
2022-04-22 07:43:00 【weixin_46272577】
题目
94. 二叉树的中序遍历
给定一个二叉树的根节点 root ,返回它的 中序遍历。

输入:root = [1,null,2,3]
输出:[1,3,2]
思路(递归)
返回规定的是vector,那么我么中序遍历的时候向vector插入元素即可,注意要使用vector<int> &v
源代码
class Solution {
public:
void midorver(TreeNode* root, vector<int> &v) {
if (root != nullptr) {
midorver(root->left, v);
v.push_back(root->val);
midorver(root->right,v);
}
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> v;
midorver(root,v);
return v;
}
};
思路(迭代)
利用栈模拟递归遍历
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> v;
stack<TreeNode*> s;
while (root != nullptr || !s.empty()) {
// 第一个包含了开始栈为空的特殊情况,且如果第一个为空指针,直接返回
while (root != nullptr) {
// 一直向左递归,知道节点为空
s.push(root);
root = root->left;
}
root = s.top();// 此时top,即为上个节点,相当于回溯上个节点
s.pop();// 弹出
v.push_back(root->val);// 保存元素
root = root->right;// 去右子树遍历
}
return v;
}
};
版权声明
本文为[weixin_46272577]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_46272577/article/details/117912791
边栏推荐
- 如何用c语言实现【猜数字游戏】
- 58 Technology Salon issue 28 - anjuke quality assurance system Salon
- On the modification of static database
- vscode的插件
- MySQL深入学习(三二):数据库其它调优策略
- Tita performance treasure: eight mistakes made by managers in performance appraisal
- One question per day: improve the mold assembly on the 15th day of sprint in the big factory
- cesium鼠标拾取要素,并判断要素类别
- ospf四类,五类和七类LSA详解
- Redis非关系型数据库—Redis高可用、持久化及性能管理
猜你喜欢
随机推荐
235. 二叉搜索树的最近公共祖先(Easy)
进程和线程
Should everyone use OKR?
Flutter Modul类与Json相互转换
Teach you how to realize the pull-down refresh and pull-up load of recyclerview
wepy学习记录
记录node中使用sequelize,自动生成表模型,链接操作数据库(以postgreSQL为例)
What do you know about the well-known public DNS servers in China
地图裁剪器,可以将图片裁剪成瓦片数据,主要用途是将高清卫星图像裁剪成瓦片图,可以做离线地图的开发,基于墨卡托坐标
MySQL in-depth study (3-2): other database tuning strategies
58 Technology Salon issue 28 - anjuke quality assurance system Salon
MaterialApp
Tita performance treasure: eight mistakes made by managers in performance appraisal
cesium中实现楼层分解动画
Fresco简单的使用—SimpleDraweeView
qt designer 跳转,布局,样式
shell脚本中ps -ef查询进程PID一直返回异常
Leetcode 111 Balanced binary tree (2022.04.21)
Cloud computing learning 2 - keystone component operation and maintenance and testing
GAVL021,GAVL281,AC220V转5V200MA小体积非隔离芯片方案








