当前位置:网站首页>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;
}
}边栏推荐
- Yolox backbone -- implementation of cspparknet
- 110. balanced binary tree recursive method
- The native applet uses canvas to make posters, which are scaled to the same scale. It is similar to the uniapp, but the writing method is a little different
- 华为路由器:ipsec技术
- 【LeetCode】415. String addition
- 从华为WeAutomate数字机器人论坛,看政企领域的“政务新智理”
- MySQL——SQL语句
- 【输入法】迄今为止,居然有这么多汉字输入法!
- Jincang KFS replicator installation (oracle-kes)
- EasyExcel单sheet页与多sheet页写出
猜你喜欢
![[noi Simulation Competition] send (tree DP)](/img/5b/3beb9f5fdad00b6d5dc789e88c6e98.png)
[noi Simulation Competition] send (tree DP)

uniapp 开发多端项目如何配置环境变量以及区分环境打包
![[quantitative investment] discrete Fourier transform to calculate array period](/img/0d/aac02463ff403fb1ff871af5ff91fa.png)
[quantitative investment] discrete Fourier transform to calculate array period

【使用 PicGo+腾讯云对象存储COS 作为图床】

用VNC Viewer的方式远程连接无需显示屏的树莓派

12、 Demonstration of all function realization effects

Yolox backbone -- implementation of cspparknet

eBanb B1手环刷固件异常中断处理

Linux MySQL installation

leetcode——错误的集合
随机推荐
520. detect capital letters
华为路由器:ipsec技术
Database migration from PostgreSQL to MySQL
Floating error waiting for changelog lock
Threejs glow channel 01 (unrealbroompass & layers)
110. balanced binary tree recursive method
当程序员被问会不会修电脑时… | 每日趣闻
Redis implements a globally unique ID
Analyze the meaning of Internet advertising terms CPM, CPC, CPA, CPS, CPL and CPR
MBA-day25 最值问题-应用题
What is graph neural network? Figure what is the use of neural networks?
从华为WeAutomate数字机器人论坛,看政企领域的“政务新智理”
YOLOX backbone——CSPDarknet的实现
【LeetCode】387. First unique character in string
Code written by mysql, data addition, deletion, query and modification, etc
数云发布2022美妆行业全域消费者数字化经营白皮书:全域增长破解营销难题
4275. Dijkstra sequence
Kaformer personal notes
解决:jmeter5.5在win11下界面上的字特别小
目标检测系列——Fast R-CNN