当前位置:网站首页>2022.06.23(LC_144,94,145_二叉树的前序、中序、后序遍历)
2022.06.23(LC_144,94,145_二叉树的前序、中序、后序遍历)
2022-06-24 07:06:00 【Leeli9316】

方法一:递归
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
preorder(root, list);
return list;
}
public void preorder(TreeNode root, List<Integer> list) {
if (root == null) return;
list.add(root.val);
preorder(root.left, list);
preorder(root.right, list);
}
}方法二:迭代
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
if (root == null) return ans;
Deque<TreeNode> stack = new LinkedList<>();
TreeNode node = root;
//遍历终止条件:当前节点为空并且栈为空
while (node != null || !stack.isEmpty()) {
while (node != null) {
stack.push(node);
ans.add(node.val);
//找到最左边的节点
node = node.left;
}
node = stack.pop();
node = node.right;
}
return ans;
}
}边栏推荐
- Increase insert speed
- Smart power plant: how to make use of easycvr to build a safe, stable, green and environment-friendly intelligent inspection platform
- leetcode 1642. Furthest Building You Can Reach(能到达的最远的建筑)
- [micro services ~nacos] Nacos service providers and service consumers
- Get screen width and height tool class
- 5 minutes, excellent customer service chat handling skills
- How to handle the problem that calling easycvr address integration cannot be played through easyplayer player?
- Several ways you can't move zero (sequel)
- 分布式 | 如何与 DBLE 进行“秘密通话”
- 图片工具
猜你喜欢

Detailed explanation of Base64 coding and its variants (to solve the problem that the plus sign changes into a space in the URL)

Send custom events in QT

ZUCC_ Principles of compiling language and compilation_ Experiment 04 language and grammar

Two methods of QT exporting PDF files

OpenCV to realize the basic transformation of image

一文讲透,商业智能BI未来发展趋势如何

ZUCC_编译语言原理与编译_实验03 编译器入门

什么是SRE?一文详解SRE运维体系

ZUCC_ Principles of compiling language and compilation_ Experiment 0607 grammar analysis ll analysis

Xiaohei ai4code code baseline nibble 1
随机推荐
利用ngrok做内网穿透
String转Base64
AUTO PWN
Get screen width and height tool class
Qt 中发送自定义事件
QPS, TPS, concurrent users, throughput relationship
Win10 cloud, add Vietnamese
Easynvr and easyrtc platforms use go language to manage projects. Summary of the use of govendor and gomod
orb slam build bug: undefined reference to symbol ‘_ ZN5boost6system15system_ categoryEv‘
Shell basic operator -- arithmetic operator
How to replace the web player easyplayerproactivex Key in OCX?
[10 day SQL introduction] Day2
One development skill a day: how to establish P2P communication based on webrtc?
Use cpulimit to free up your CPU
数据平台简介
ZUCC_ Principles of compiling language and compilation_ Experiment 08 parsing LR parsing
Live broadcast appointment: growth of Mengxin Product Manager
【力扣10天SQL入门】Day2
数据库迁移从PostgreSQL迁移到 MYSQL
解析互联网广告术语 CPM、CPC、CPA、CPS、CPL、CPR 是什么意思