当前位置:网站首页>【LeetCode】94.二叉树的中序遍历
【LeetCode】94.二叉树的中序遍历
2022-08-02 02:40:00 【酥酥~】
题目
给定一个二叉树的根节点 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;
}
};
边栏推荐
猜你喜欢

Nanoprobes纳米探针丨Nanogold偶联物的特点和应用

KICAD 小封装拉线卡顿问题 解决方法

忽晴忽雨

How engineers treat open source

The state status is displayed incorrectly after the openGauss switch

The principle and code implementation of intelligent follower robot in the actual combat of innovative projects

第11章_数据库的设计规范

工程师如何对待开源

analog IC layout

Flask之路由(app.route)详解
随机推荐
简单的页面跳转活动
Flask入门学习教程
一次SQL优化,数据库查询速度提升 60 倍
详解最强分布式锁工具:Redisson
Analysis of the status quo of digital transformation of manufacturing enterprises
2022-08-01 Install mysql monitoring tool phhMyAdmin
Good News | AR opens a new model for the textile industry, and ALVA Systems wins another award!
JVM调优实战
IPFS部署及文件上传(golang)
【Unity入门计划】2D Game Kit:初步了解2D游戏组成
第10章_索引优化与查询优化
The state status is displayed incorrectly after the openGauss switch
51. 数字排列
Curriculum Vitae;CV
Docker-compose安装mysql
Nanoprobes丨1-巯基-(三甘醇)甲醚功能化金纳米颗粒
OC中new和init的区别
[ORB_SLAM2] SetPose, UpdatePoseMatrices
周鸿祎称微软抄袭,窃取360安全模式
2022-08-01 Reflection