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

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

指针数组和数组指针

BI - SQL 丨 WHILE

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

CASE2023

国标GB28181协议EasyGBS平台兼容老版本收流端口的功能实现

【每日一道LeetCode】——1. 两数之和

Good News | AR opens a new model for the textile industry, and ALVA Systems wins another award!

使用DBeaver进行mysql数据备份与恢复

FOFAHUB使用测试
随机推荐
【LeetCode】145.二叉树的后序遍历
esp32经典蓝牙和单片机连接,,,手机蓝牙作为主机
Recursively check if a configuration item has changed and replace it
How engineers treat open source
OC中成员变量,实例变量和属性之间的区别和联系
四元数、罗德里格斯公式、欧拉角、旋转矩阵推导和资料
Use DBeaver for mysql data backup and recovery
Entry name 'org/apache/commons/codec/language/bm/gen_approx_greeklatin.txt' collided
Reflex WMS Intermediate Series 7: What should I do if I want to cancel the picking of an HD that has finished picking but has not yet been loaded?
JS中获取对象数据类型的键值对的键与值
NIO's Sword
局部敏感哈希:如何在常数时间内搜索Embedding最近邻
Service discovery of kubernetes
微服务:微智能在软件系统的简述
AcWing 1285. Word Problem Solving (AC Automata)
Chapter 7 Noise analysis
【LeetCode】104.二叉树的最大深度
字典常用方法
启发式合并、DSU on Tree
网络层解析——IP协议、地址管理、路由选择