当前位置:网站首页>2022.06.23 (traversal of lc_144,94145\
2022.06.23 (traversal of lc_144,94145\
2022-06-24 09:08:00 【Leeli9316】

Method 1 : recursive
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);
}
}Method 2 : iteration
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;
// Traversal termination conditions : The current node is empty and the stack is empty
while (node != null || !stack.isEmpty()) {
while (node != null) {
stack.push(node);
ans.add(node.val);
// Find the leftmost node
node = node.left;
}
node = stack.pop();
node = node.right;
}
return ans;
}
}边栏推荐
- 2138. splitting a string into groups of length k
- eBanb B1手环刷固件异常中断处理
- [redis implements seckill business ①] seckill process overview | basic business implementation
- [e325: attention] VIM editing error
- 华为路由器:GRE技术
- Data middle office: overview of data governance
- 十二、所有功能实现效果演示
- How to configure environment variables and distinguish environment packaging for multi terminal project of uniapp development
- 520. detect capital letters
- Floating error waiting for changelog lock
猜你喜欢

嵌入式 | 硬件转软件的几条建议

Become an IEEE student member

4274. suffix expression

cookie加密 4 rpc方法确定cookie加密

Kaformer personal notes

What is graph neural network? Figure what is the use of neural networks?

Yolox backbone -- implementation of cspparknet

华为路由器:ipsec技术
![[redis realize Secondary killing Business ①] Overview of Secondary killing Process | Basic Business Realization](/img/a3/9a50e83ece43904a3a622dcdb05b3c.png)
[redis realize Secondary killing Business ①] Overview of Secondary killing Process | Basic Business Realization

Huawei Router: GRE Technology
随机推荐
Double pointer analog
Solution: the word of jmeter5.5 on the win11 lower interface is very small
Squid proxy application
十二、所有功能实现效果演示
陆奇:我现在最看好这四大技术趋势
小白学习MySQL - 增量统计SQL的需求
关于 GIN 的路由树
"I can't understand Sudoku, so I choose to play Sudoku."
Idea another line shortcut
当程序员被问会不会修电脑时… | 每日趣闻
MySQL - SQL statement
520. detect capital letters
【Redis實現秒殺業務①】秒殺流程概述|基本業務實現
Wan Weiwei, a researcher from Osaka University, Japan, introduced the rapid integration method and application of robot based on WRS system
Data middle office: middle office architecture and overview
Mba-day25 best value problem - application problem
普通人没有学历,自学编程可以月入过万吗?
4275. Dijkstra序列
GradScaler MaxClipGradScaler
开源之夏中选名单已公示,基础软件领域成为今年的热门申请