当前位置:网站首页>力扣-二叉树的前序遍历、中序遍历、后序遍历
力扣-二叉树的前序遍历、中序遍历、后序遍历
2022-08-05 02:00:00 【qq_52025208】
一、题目描述:给你二叉树的根节点 root ,返回它节点值的 前序 遍历。
1.递归:
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> preorderTraversal(TreeNode root) {
if(root == null) return list;
list.add(root.val);
preorderTraversal(root.left);
preorderTraversal(root.right);
return list;
}
}
2.非递归
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<>();
if(root==null) return list;
Stack<TreeNode> stack=new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node= stack.pop();
list.add(node.val);
if(node.right!=null){
stack.push(node.right);
}
if(node.left!=null){
stack.push(node.left);
}
}
return list;
}
}
二、中序遍历
递归:
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null) return list;
inorderTraversal(root.left);
list.add(root.val);
inorderTraversal(root.right);
return list;
}
}
非递归:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root == null) return list;
Stack<TreeNode> stack = new Stack<>();
while(root != null || !stack.empty()) {
while(root!= null) {
stack.push(root);
root = root.left;
}
root = stack.pop();
list.add(root.val);
root = root.right;
}
return list;
}
}
三、后序遍历
class Solution {
List<Integer> list = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if(root == null) return list;
postorderTraversal(root.left);
postorderTraversal(root.right);
list.add(root.val);
return list;
}
}
边栏推荐
猜你喜欢
【Endnote】Word插入自定义形式的Endnote文献格式
Hypervisor related knowledge points
[Unity Entry Plan] Handling of Occlusion Problems in 2D Games & Pseudo Perspective
KingbaseES V8 GIS数据迁移方案(2. Kingbase GIS能力介绍)
".NET IoT from scratch" series
汇编语言之源程序
2022 EdgeX中国挑战赛8月3日即将盛大开幕
Tree search (bintree)
【七夕如何根据情侣倾听的音乐进行薅羊毛】背景音乐是否会影响情侣对酒的选择
[Endnote] Word inserts a custom form of Endnote document format
随机推荐
如何看待自己的羞愧感
C language basics -- pointers
Hypervisor related knowledge points
树形查找(二叉查找树)
缺陷检测(图像处理部分)
Exercise: Selecting a Structure (1)
CMS建站流程
[Machine Learning] 21-day Challenge Study Notes (2)
Greenplum数据库故障分析——能对数据库base文件夹进行软连接嘛?
一文看懂推荐系统:召回06:双塔模型——模型结构、训练方法,召回模型是后期融合特征,排序模型是前期融合特征
std::string::find 返回值的坑
为什么他们选择和AI恋爱?
ExcelPatternTool: Excel表格-数据库互导工具
the mechanism of ideology
Why is this problem reported when installing oracle11
Is DDOS attack really unsolvable?Do not!
【Unity入门计划】2D游戏中遮挡问题的处理方法&伪透视
【七夕如何根据情侣倾听的音乐进行薅羊毛】背景音乐是否会影响情侣对酒的选择
海量服务实例动态化管理
day14--postman接口测试