当前位置:网站首页>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;
}
}边栏推荐
- leetcode 1268. Search Suggestions System(搜索推荐系统)
- [acnoi2022] not a structure, more like a structure
- 2021-06-25: a batch of strings consisting only of lowercase letters (a~z) are put
- 饼状统计图,带有标注线,都可以自行设定其多种参数选项
- String转Base64
- After interviewing and tutoring several children, I found some problems!
- Rescue system -- the application of read-write separation
- String to Base64
- Shell basic operator -- arithmetic operator
- Ordinary token
猜你喜欢

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

pymysql 向MySQL 插入数据无故报错

MySQL 因字符集问题插入中文数据时提示代码 :1366

MATLAB Camera Calibrator相机标定

ZUCC_ Principles of compiling language and compilation_ Experiment 08 parsing LR parsing

ZUCC_ Principles of compiling language and compilation_ Experiment 05 regular expression, finite automata, lexical analysis

【关于运维和网工的差别,一文说透】

小黑ai4code代码baseline啃食1

一文详解|增长那些事儿

Redis的Cluster集群数据倾斜
随机推荐
单目双视三维坐标确定
Live broadcast appointment: growth of Mengxin Product Manager
提高INSERT速度
Building a static website with eleventy
[untitled]
Common misconceptions in Tencent conference API - signature error_ code 200003
Ordering of MySQL composite index
How to replace the web player easyplayerproactivex Key in OCX?
There was an error checking the latest version of pip
Redis cluster data skew
Redis的Cluster集群数据倾斜
5 minutes, excellent customer service chat handling skills
How to implement approval function in Tekton
ZUCC_ Principles of compiling language and compilation_ Big job
Smart power plant: how to make use of easycvr to build a safe, stable, green and environment-friendly intelligent inspection platform
【力扣10天SQL入门】Day3
String to Base64
"Adobe international certification" Photoshop software, about drawing tutorial?
Pyqt common system events
Earthly 容器镜像构建工具 —— 筑梦之路