当前位置:网站首页>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;
}
}
边栏推荐
- RuntimeError: Missing dependencies:XXX
- 日本大阪大学万伟伟研究员介绍基于WRS系统机器人的快速集成方法和应用
- Increase insert speed
- 深度学习与神经网络:最值得关注的6大趋势
- leetcode 1268. Search suggestions system
- There was an error checking the latest version of pip
- Qt源码分析--QObject(2)
- 分布式 | 如何与 DBLE 进行“秘密通话”
- QPS, TPS, concurrent users, throughput relationship
- Using sonar for code checking
猜你喜欢
ZUCC_ Principles of compiling language and compilation_ Experiment 04 language and grammar
分布式 | 如何与 DBLE 进行“秘密通话”
Detailed explanation of Base64 coding and its variants (to solve the problem that the plus sign changes into a space in the URL)
Fundamentals of 3D mathematics [17] inverse square theorem
關於ETL看這篇文章就够了,三分鐘讓你明白什麼是ETL
ZUCC_ Principles of compiling language and compilation_ Experiment 02 fsharp Ocaml language
Two methods of QT exporting PDF files
什么是SRE?一文详解SRE运维体系
Centos7 installation of jdk8, mysql5.7 and Navicat connection to virtual machine MySQL and solutions (solutions to MySQL download errors are attached)
Permission model DAC ACL RBAC ABAC
随机推荐
【团队管理】测试团队绩效管理的25点小建议
[acnoi2022] not a structure, more like a structure
Introduction to NC machine tool programming [G-code]
Maya re deployment
Blue screen error UNMOUNTABLE boot volume of the solution
分布式 | 如何与 DBLE 进行“秘密通话”
RuntimeError: Missing dependencies:XXX
[xinliu-s6 new model +sa 3-star Xinghai] the new two-way server of the third generation chip was launched and the product was updated~
5 minutes, excellent customer service chat handling skills
rsync做文件备份
There was an error checking the latest version of pip
ZUCC_编译语言原理与编译_实验06 07 语法分析 LL 分析
Use cpulimit to free up your CPU
Using ngrok for intranet penetration
QT source code analysis -- QObject (2)
Micro build low code online "quick registration applet" capability
【关于运维和网工的差别,一文说透】
xargs使用技巧 —— 筑梦之路
K8S部署高可用postgresql集群 —— 筑梦之路
orb slam build bug: undefined reference to symbol ‘_ ZN5boost6system15system_ categoryEv‘