链表、二叉树—递归遍历框架
注意:
前中后序是遍历二叉树过程中处理每一个节点的三个特殊时间点
前序:刚刚进入一个节点执行
中序:左子树全部执行完,准备执行右子树前
后续:离开节点前执行
二叉树前中后序遍历框架
1.递归框架
void traverse(TreeNode head){
if(head==null){
return;
}
//前序遍历
traverse(head.left);
//中序遍历
traverse(head.right);
//后续遍历
}
2.迭代框架
先序遍历
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while(root!=null||!stack.isEmpty()){
while(root!=null){
res.add(root.val);
stack.push(root);
root=root.left;
}
root=stack.pop().right;
}
return res;
}
}
中序遍历
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> res=new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while(root!=null||!stack.isEmpty()){
while(root!=null){
stack.push(root);
root=root.left;
}
res.add(stack.peek().val);
root=stack.pop().right;
}
return res;
}
}
后序遍历
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode alreadyVisited = null;
while (root != null || !stack.isEmpty()) {
while (root != null) {
stack.push(root);
root = root.left;
}
TreeNode node= stack.peek();
if (node.right != null && node.right != alreadyVisited) {
root = node.right;
} else {
node= stack.pop();
res.add(node.val);
alreadyVisited = node;
}
}
return res;
}
链表递归遍历框架
void traverse(ListNode head){
if(head==null){
return head;
}
//正序遍历
traverse(head.next);
//逆序遍历
}
不说废话先做题
class Solution {
//保存返回结果
int res=0;
//记录二叉树层数
int floor=0;
void traverse(TreeNode head){
if(head==null){
res=Math.max(floor,res);
return;
}
//第一次进入节点 我就开始floor++
floor++;
traverse(head.left);
traverse(head.right);
//离开节点的时候floor--
floor--;
}
public int maxDepth(TreeNode root) {
traverse(root);
return res;
}
}
递归版本分解问题
class Solution {
int max(TreeNode head){
if(head==null){
return 0;
}
int maxLeft=max(head.left);
int maxRight=max(head.right);
return Math.max(maxLeft,maxRight)+1;
}
public int maxDepth(TreeNode root) {
return max(root);
}
}
本文来自博客园,作者:帅气的涛啊,转载请注明原文链接:https://www.cnblogs.com/handsometaoa/p/15992186.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)