当前位置:网站首页>【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;
}
};
边栏推荐
猜你喜欢
Install mysql using docker
【web】Understanding Cookie and Session Mechanism
局部敏感哈希:如何在常数时间内搜索Embedding最近邻
【web】理解 Cookie 和 Session 机制
How engineers treat open source
analog IC layout-Design for reliability
[Unity entry plan] 2D Game Kit: A preliminary understanding of the composition of 2D games
FOFAHUB usage test
网络层解析——IP协议、地址管理、路由选择
Outsourcing worked for three years, it was abolished...
随机推荐
pyqt上手体验
Curriculum Vitae;CV
四元数、罗德里格斯公式、欧拉角、旋转矩阵推导和资料
Nanoprobes纳米探针丨Nanogold偶联物的特点和应用
2022.8.1-----leetcode.1374
2022 NPDP take an examination of how the results?How to query?
BI - SQL 丨 WHILE
The principle and code implementation of intelligent follower robot in the actual combat of innovative projects
Nanoprobes丨1-巯基-(三甘醇)甲醚功能化金纳米颗粒
一次SQL优化,数据库查询速度提升 60 倍
analog IC layout
Flask之路由(app.route)详解
2022牛客多校四_G M
ALCCIKERS Shane 20191114
罗德里格斯公式(Rodrigues‘ Rotation Formula)推导
微服务:微智能在软件系统的简述
【每日一道LeetCode】——9. 回文数
Talking about the "horizontal, vertical and vertical" development trend of domestic ERP
记一个gorm初始化的坑
Service discovery of kubernetes