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

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

Remember a pit for gorm initialization

四元数、罗德里格斯公式、欧拉角、旋转矩阵推导和资料

Analysis of the status quo of digital transformation of manufacturing enterprises

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

Pinduoduo leverages the consumer expo to promote the upgrading of domestic agricultural products brands and keep pace with international high-quality agricultural products

analog IC layout-Environmental noise

【web】理解 Cookie 和 Session 机制

GTK RGB图像绘制

Electronic Manufacturing Warehouse Barcode Management System Solution
随机推荐
* 比较版本号
架构:应用架构的演进以及微服务架构的落地实践
Swift运行时(派发机制)
pyqt上手体验
2022年NPDP考完多久出成绩?怎么查询?
使用docker安装mysql
C#测试项目中属性的用法
BioVendor Human Club Cellular Protein (CC16) Elisa Kit Research Fields
接口测试神器Apifox究竟有多香?
NIO‘s Sword(牛客多校赛)
剑指 Offer 14- I. 剪绳子
【LeetCode】83.删除排序链表中的重复元素
(一)Redis: 基于 Key-Value 的存储系统
JVM调优实战
【web】Understanding Cookie and Session Mechanism
Flask 报错:WARNING This is a development server. Do not use it in a production deployment
cocos中使用async await异步加载资源
BioVendor人俱乐部细胞蛋白(CC16)Elisa试剂盒研究领域
最大层内元素和
Nacos源码分析专题(一)-环境准备