当前位置:网站首页>[LeetCode] 94. Inorder traversal of binary tree
[LeetCode] 94. Inorder traversal of binary tree
2022-08-02 02:46:00 【Cake cake ~】
题目
给定一个二叉树的根节点 root ,返回 它的 中序 遍历 .
示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1,2,3,4,5,6,7]
输出:[4,2,5,1,6,3,7]
提示:
树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
题解
深度优先遍历
递归方法
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class Solution {
public:
void fun(TreeNode* node,vector<int> &result)
{
if(node->left)
fun(node->left,result);
result.emplace_back(node->val);
if(node->right)
fun(node->right,result);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
if(root)
fun(root,result);
return result;
}
};
迭代方法
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> mystack;
TreeNode* node = root;
while(!mystack.empty() || node!=nullptr)
{
while(node!=nullptr)
{
if(node)
mystack.emplace(node);
node = node->left;
}
node = mystack.top();
mystack.pop();
result.emplace_back(node->val);
node = node->right;
}
return result;
}
};
边栏推荐
- 架构:应用架构的演进以及微服务架构的落地实践
- 递归检查配置项是否更变并替换
- 搭建zabbix监控及邮件报警(超详细教学)
- Moonbeam and Project integration of the Galaxy, bring brand-new user experience for the community
- 【web】Understanding Cookie and Session Mechanism
- 第11章_数据库的设计规范
- 【Unity入门计划】2D Game Kit:初步了解2D游戏组成
- 面对职场“毕业”,PM&PMO应该如何从容的应对?如何跳槽能够大幅度升职加薪?
- How ReentrantLock works
- FOFAHUB usage test
猜你喜欢

Nanoprobes免疫测定丨FluoroNanogold试剂免疫染色方案

KICAD 拉线宽度无法修改,解决方法

esp32经典蓝牙和单片机连接,,,手机蓝牙作为主机

永磁同步电机36问(三)——SVPWM代码实现

ReentrantLock工作原理

Flask入门学习教程

Nanoprobes丨1-mercapto-(triethylene glycol) methyl ether functionalized gold nanoparticles

AI目标分割能力,无需绿幕即可实现快速视频抠图

机器人领域期刊会议汇总

【web】Understanding Cookie and Session Mechanism
随机推荐
搭建zabbix监控及邮件报警(超详细教学)
【LeetCode】104.二叉树的最大深度
Flask 报错:WARNING This is a development server. Do not use it in a production deployment
Oracle19c安装图文教程
Moonbeam and Project integration of the Galaxy, bring brand-new user experience for the community
【Unity入门计划】2D Game Kit:初步了解2D游戏组成
【每日一道LeetCode】——9. 回文数
Safety (2)
字典常用方法
Nacos源码分析专题(二)-服务注册
C#测试项目中属性的用法
NIO‘s Sword(牛客多校赛)
analog IC layout
aws s3上传文件
Nanoprobes多组氨酸 (His-) 标签标记:重组蛋白检测方案
使用DBeaver进行mysql数据备份与恢复
菜刀webshell特征分析
启发式合并、DSU on Tree
Analysis of the status quo of digital transformation of manufacturing enterprises
29. 删除链表中重复的节点