当前位置:网站首页>Likou - preorder traversal, inorder traversal, postorder traversal of binary tree
Likou - preorder traversal, inorder traversal, postorder traversal of binary tree
2022-08-05 02:43: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;
}
}
边栏推荐
- lua learning
- 行业案例|世界 500 强险企如何建设指标驱动的经营分析系统
- 北斗三号短报文终端露天矿山高边坡监测方案
- The 20th day of the special assault version of the sword offer
- Simple implementation of YOLOv7 pre-training model deployment based on OpenVINO toolkit
- Advanced Numbers_Review_Chapter 1: Functions, Limits, Continuity
- 力扣-相同的树
- Pisanix v0.2.0 发布|新增动态读写分离支持
- 【LeetCode刷题】-数之和专题(待补充更多题目)
- 【解密】OpenSea免费创造的NFT都没上链竟能出现在我的钱包里?
猜你喜欢
随机推荐
你要的七夕文案,已为您整理好!
lua learning
ARM Mailbox
LeetCode uses the minimum cost to climb the stairs----dp problem
Advanced Numbers_Review_Chapter 1: Functions, Limits, Continuity
SuperMap iDesktop.Net之布尔运算求交——修复含拓扑错误复杂模型
学习笔记-----左偏树
C语言日记 9 if的3种语句
torch.roll()
软链接引发的物理备份问题
Gantt chart is here, project management artifact, template is used directly
甘特图来啦,项目管理神器,模板直接用
Pisanix v0.2.0 发布|新增动态读写分离支持
Apache DolphinScheduler新一代分布式工作流任务调度平台实战-中
RAID磁盘阵列
02 [Development Server Resource Module]
基于左序遍历的数据存储实践
线性表的查找
Multithreading (2)
C学生管理系统 头添加学生节点








![01 [Foreword Basic Use Core Concepts]](/img/90/67537d5fad28d68766ca85b887839e.png)
