当前位置:网站首页>【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;
}
};
边栏推荐
猜你喜欢

Service discovery of kubernetes

2022 Henan Youth Training League Game (3)

网络层解析——IP协议、地址管理、路由选择

51. 数字排列

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

EasyGBS平台播放视频时偶尔出现播放失败是什么原因?

The failure to create a role in Dahua Westward Journey has been solved

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

analog IC layout-Environmental noise

很有意思的经历,很有意思的项目--文件夹对比工具
随机推荐
Moonbeam and Project integration of the Galaxy, bring brand-new user experience for the community
【CNN记录】tensorflow slice和strided_slice
EasyGBS平台播放视频时偶尔出现播放失败是什么原因?
字符串常用方法
2022-08-01 Reflection
列表常用方法
Nanoprobes Polyhistidine (His-) Tag: Recombinant Protein Detection Protocol
数仓:为什么说 ETL 的未来不是 ELT,而是 EL (T)
2022.8.1-----leetcode.1374
MySQL索引优化实战
Analysis of the status quo of digital transformation of manufacturing enterprises
Oracle数据类型介绍
Nacos源码分析专题(二)-服务注册
The principle and code implementation of intelligent follower robot in the actual combat of innovative projects
Curriculum Vitae;CV
Flask 报错:WARNING This is a development server. Do not use it in a production deployment
MySQL - CRUD operations
2022-07-30 mysql8 executes slow SQL-Q17 analysis
2022 Henan Youth Training League Game (3)
How engineers treat open source