当前位置:网站首页>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;
}
}边栏推荐
- lombok 使用
- 【生活思考】计划与自律
- How to mount a USB hard disk with NTFS file format under RHEL5 system
- 分布式 | 如何与 DBLE 进行“秘密通话”
- Battle history between redis and me under billion level traffic
- [explain the difference between operation and maintenance and network engineering]
- How to handle the problem that calling easycvr address integration cannot be played through easyplayer player?
- dataX使用指南
- Centos7 installation of jdk8, mysql5.7 and Navicat connection to virtual machine MySQL and solutions (solutions to MySQL download errors are attached)
- Use cpulimit to free up your CPU
猜你喜欢

Send custom events in QT

小黑ai4code代码baseline啃食1

Base64编码详解及其变种(解决加号在URL变空格问题)

pymysql 向MySQL 插入数据无故报错
![[micro services ~nacos] Nacos service providers and service consumers](/img/b7/47ecd6979ccfeb270261681d6130be.png)
[micro services ~nacos] Nacos service providers and service consumers

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

關於ETL看這篇文章就够了,三分鐘讓你明白什麼是ETL

A preliminary study of IO model

中国芯片独角兽公司

关于ETL看这篇文章就够了,三分钟让你明白什么是ETL
随机推荐
什么是SRE?一文详解SRE运维体系
Redis的Cluster集群数据倾斜
Qt 中发送自定义事件
成为IEEE学生会员
How to handle the problem that calling easycvr address integration cannot be played through easyplayer player?
leetcode 1642. Furthest Building You Can Reach(能到达的最远的建筑)
【力扣10天SQL入门】Day2
[real estate opening online house selection, WiFi coverage temporary network] 500 people are connected to WiFi at the same time
图片工具
RuntimeError: Missing dependencies:XXX
Blue screen error UNMOUNTABLE boot volume of the solution
Rsync for file backup
[life thinking] planning and self-discipline
Several ways you can't move zero (sequel)
Distributed | how to make "secret calls" with dble
Shell pass parameters
Rescue system -- the application of read-write separation
5 minutes, excellent customer service chat handling skills
数据平台简介
Background management of uniapp hot update