树的遍历实现

news/2025/9/30 20:39:40/文章来源:https://www.cnblogs.com/jiangbyte/p/19121740

LeetCode 144. 二叉树的前序遍历

前序遍历的顺序是:根节点 → 左子树 → 右子树

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;public class BinaryTreePreorderTraversal {public static void main(String[] args) {Solution solution = new BinaryTreePreorderTraversal().new Solution();}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) {this.val = val;}TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}class Solution {public List<Integer> preorderTraversal(TreeNode root) {List<Integer> result = new ArrayList<>();
//        traversal(root, result);
//        return result;return traversal(root);}// 遍历(递归实现)public void traversal(TreeNode root, List<Integer> result) {if (root == null) {return;}result.add(root.val); // 前序遍历在这里添加根节点traversal(root.left, result);traversal(root.right, result);}// 遍历(迭代实现)public List<Integer> traversal(TreeNode root) {List<Integer> result = new ArrayList<>();if (root == null) {return result;}Stack<TreeNode> stack = new Stack<>();// 根节点入栈stack.push(root);// 栈不为空,则继续遍历while (!stack.isEmpty()) {TreeNode node = stack.pop();result.add(node.val); // 访问根节点// 入栈 根右左,出栈 根左右// 先将右节点入栈if (node.right != null) {stack.push(node.right);}// 再将左节点入栈if (node.left != null) {stack.push(node.left);}}return result;}}
}

迭代写法二

class Solution {public List<Integer> preorderTraversal(TreeNode root) {List<Integer> result = new ArrayList<>();Stack<TreeNode> stack = new Stack<>();TreeNode curr = root;while (curr != null || !stack.isEmpty()) {// 一直往左走,边走边访问while (curr != null) {result.add(curr.val); // 访问当前节点stack.push(curr);     // 保存节点用于后续访问右子树curr = curr.left;     // 移动到左子节点}// 回溯到上一个节点并转向右子树curr = stack.pop();curr = curr.right;}return result;}
}

LeetCode 94. 二叉树的中序遍历

中序遍历的顺序是:左子树 → 根节点 → 右子树

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;public class BinaryTreeInorderTraversal {public static void main(String[] args) {Solution solution = new BinaryTreeInorderTraversal().new Solution();}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) {this.val = val;}TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}class Solution {public List<Integer> inorderTraversal(TreeNode root) {List<Integer> result = new ArrayList<>();
//        traversal(root, result);
//        return result;return traversal(root);}// 遍历(递归实现)public void traversal(TreeNode root, List<Integer> result) {if (root == null) {return;}traversal(root.left, result);result.add(root.val); // 中序遍历在这里添加根节点(但是不是本题目)traversal(root.right, result);}public List<Integer> traversal(TreeNode root) {List<Integer> result = new ArrayList<>();Stack<TreeNode> stack = new Stack<>();TreeNode curr = root;while (curr != null || !stack.isEmpty()) {// 一直往左走,把所有左子节点入栈while (curr != null) {stack.push(curr);curr = curr.left;}// 弹出栈顶节点(最左边的节点)curr = stack.pop();result.add(curr.val); // 访问当前节点// 转向右子树curr = curr.right;}return result;}}
}

迭代写法二

class Solution {public List<Integer> inorderTraversal(TreeNode root) {List<Integer> result = new ArrayList<>();if (root == null) {return result;}Stack<TreeNode> stack = new Stack<>();TreeNode curr = root;while (curr != null || !stack.isEmpty()) {if (curr != null) {stack.push(curr);curr = curr.left; // 先处理左子树} else {curr = stack.pop();result.add(curr.val); // 访问根节点curr = curr.right;    // 再处理右子树}}return result;}
}

统一的迭代写法

class Solution {public List<Integer> inorderTraversal(TreeNode root) {List<Integer> result = new ArrayList<>();if (root == null) {return result;}Stack<TreeNode> stack = new Stack<>();stack.push(root);while (!stack.isEmpty()) {TreeNode node = stack.pop();if (node != null) {// 右子节点入栈if (node.right != null) {stack.push(node.right);}// 当前节点再次入栈,前面加一个null标记stack.push(node);stack.push(null);// 左子节点入栈if (node.left != null) {stack.push(node.left);}} else {// 遇到null标记,弹出下一个节点并访问node = stack.pop();result.add(node.val);}}return result;}
}

LeetCode 145. 二叉树的后序遍历

后序遍历的顺序是:左子树 → 右子树 → 根节点

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;public class BinaryTreePostorderTraversal {public static void main(String[] args) {Solution solution = new BinaryTreePostorderTraversal().new Solution();}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) {this.val = val;}TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}class Solution {public List<Integer> postorderTraversal(TreeNode root) {List<Integer> result = new ArrayList<>();
//        traversal(root, result);
//        return result;return traversal(root);}// 遍历(递归实现)public void traversal(TreeNode root, List<Integer> result) {if (root == null) {return;}traversal(root.left, result);traversal(root.right, result);result.add(root.val); // 后序遍历在这里添加根节点}public List<Integer> traversal(TreeNode root) {List<Integer> result = new ArrayList<>();if (root == null) {return result;}Stack<TreeNode> stack = new Stack<>();stack.push(root);while (!stack.isEmpty()) {TreeNode node = stack.pop();result.add(node.val);if (node.left != null) {stack.push(node.left);}if (node.right != null) {stack.push(node.right);}}// 翻转结果Collections.reverse(result);return result;}}
}

迭代写法二

class Solution {public List<Integer> postorderTraversal(TreeNode root) {List<Integer> result = new ArrayList<>();if (root == null) {return result;}Stack<TreeNode> stack = new Stack<>();TreeNode curr = root;TreeNode prev = null; // 记录上一个访问的节点while (curr != null || !stack.isEmpty()) {// 一直往左走while (curr != null) {stack.push(curr);curr = curr.left;}curr = stack.peek();// 如果右子树为空或者右子树已经访问过,则访问当前节点if (curr.right == null || curr.right == prev) {result.add(curr.val);stack.pop();prev = curr;curr = null; // 当前节点处理完毕,继续回溯} else {// 转向右子树curr = curr.right;}}return result;}
}

双栈法

class Solution {public List<Integer> postorderTraversal(TreeNode root) {List<Integer> result = new ArrayList<>();if (root == null) {return result;}Stack<TreeNode> stack1 = new Stack<>();Stack<TreeNode> stack2 = new Stack<>();stack1.push(root);while (!stack1.isEmpty()) {TreeNode node = stack1.pop();stack2.push(node); // 将节点压入第二个栈// 先左后右,这样第二个栈出栈时就是先右后左if (node.left != null) {stack1.push(node.left);}if (node.right != null) {stack1.push(node.right);}}// 从第二个栈弹出,得到后序遍历结果while (!stack2.isEmpty()) {result.add(stack2.pop().val);}return result;}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/923230.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

张家港英文网站制作惠州做网站 百度优化

文章目录一、MySQL数据库备份单循环1. 安装mysql2. 配置mysql环境变量3. 刷新环境变量4. 创建数据库和表lue5. 脚本制作6. 运行脚本7. 查看备份的sql文件7. 脚本升级动态传参8. 运行脚本9. 查看备份的sql文件二、MySQL数据库表备份多循环2.1. 脚本制作2.2. 运行脚本2.3. 指定目…

福田区住房和建设局网站网站要实名认证

目录 1.概念2.结构3.实现4.优缺点5.使用场景6.模式扩展7.JDK 源码解析——Collection.iterator 方法 1.概念 &#xff08;1&#xff09;Java 设计模式——工厂方法模式中考虑的是一类产品的生产&#xff0c;如畜牧场只养动物、电视机厂只生产电视机等。这些工厂只生产同种类产…

企业网站在ps里做吗wordpress 点击文章图片

第1章&#xff1a;引言 大家好&#xff0c;我是小黑&#xff0c;今天咱们要聊聊Lock Support。Lock Support是Java并发编程的一块基石&#xff0c;它提供了一种非常底层的线程阻塞和唤醒机制&#xff0c;是许多高级同步工具的基础。 为什么要关注Lock Support&#xff1f;线程…

自媒体网站源码google store

del dict[key] # 删除dict字典里的键值

题解:AT_abc311_h [ABC311Ex] Many Illumination Plans

题意:给出一棵树,每个节点有权值,重量和颜色,问对于每个子树 \(u\),选出一个包含 \(u\) 的虚树,满足重量之和 \(\le X\),相邻两个点颜色不同且权值和最大。 做法: 首先我们会一个非常平凡的 \(O(nX^2)\) 做法,…

怎么在阿里云服务器上建设网站网站数据模版

知识导航&#xff08;就问全不全&#xff09; 当学习 Vue.js 时&#xff0c;除了基本的 HTML、CSS 和 JavaScript 知识外&#xff0c;还有一些其他的技术和语法需要了解&#xff0c;例如 ES6 和 TypeScript。以下是您可能需要学习的一些基础知识和对应的学习资源&#xff0c;我…

上海网站设计图片新建网址

没有使用Windows经典风格的QTreeView或QTreeWidget显示如下&#xff1a; 使用Windows经典风格的QTreeView或QTreeWidget显示如下&#xff1a; 树展开时&#xff1a; 树未展开时&#xff1a; 可以看到&#xff1a; 未使用Windows经典风格时&#xff0c;QTreeView或QTreeWidget…

南阳网站建设aokuo做图网站有哪些

随着人工智能的迅猛发展&#xff0c;ChatGPT作为一种强大的自然语言处理模型&#xff0c;逐渐在学术界引起了广泛的关注。本文将探讨ChatGPT在学术写作中的应用&#xff0c;并分享使用ChatGPT进行学术写作时的一些经验和心得。 01 — ChatGPT在学术写作中的应用 1.文献综述和…

淮南移动网站建设深圳网站推广优化

区域代理的保护机制&#xff1a;在链动商城系统里设定的代理有唯一性&#xff0c;每个省只有一个省代&#xff0c;每个市只有一个市代&#xff0c;每个区县只有一个区县代。这样也是保护每个代理的收益权益。 区域代理包含的权益类别&#xff1a;购物奖励折扣&#xff1b;区域实…

品牌网站建设哪里有维影企业网站管理系统

基于springboot实现酒店客房管理平台系统演示 摘 要 随着人们的物质水平的提高&#xff0c;旅游业和酒店业发展的速度越来越快。近年来&#xff0c;市面上酒店的数量和规模都在不断增加&#xff0c;如何提高酒店的管理效率和服务质量成为了一个重要的问题。伴随着信息技术的发…

易语言如何做网站钦州建设网站

题目 给定长为n(n<2e5)的1-n的排列p&#xff0c; 求(i,j)(1<i<j<n)对的数量&#xff0c;满足gcd(i,j)≠1且gcd(pi,pj)≠1 思路来源 官方题解 题解 参考莫比乌斯函数mu&#xff0c;定义一个新函数&#xff0c; 新函数需要满足n1的时候对因子求和为0&#xff0…

现在流行的网站开发中关村在线

简介&#xff1a; 针对数据库连接池到DRDS连接探活的优化 1. 问题背景 近期在给某专有云客户进⾏云产品应⽤性能优化分析时&#xff0c;发现了⼀个有趣的关于DRDS使⽤层⾯的问题&#xff0c;这⾥给⼤家分享⼀下。 使⽤过DRDS产品的同学都知道在DRDS中&#xff0c;未分库分表的…

2025-9-27 提高组模拟赛 div2

比赛链接模拟赛 订正赛

idea 网站开发网站页面设计制作费

随着世界技术的迭代与发展&#xff0c;人工智能和机器学习正在超自动化领域&#xff0c;扮演着越来越重要的角色。2020年的冠状病毒疫情突发&#xff0c;整个世界都在防疫的道路上披荆斩棘。人工智能发挥了重大作用&#xff0c;智能测温、智能消毒、智能建设都能看到AI的影子。…

植物大战僵尸融合版下载安装教程【PC/安卓/iOS 完整攻略 + 常见问题解决】 - 详解

植物大战僵尸融合版下载安装教程【PC/安卓/iOS 完整攻略 + 常见问题解决】 - 详解pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font…

合同范本的网站深圳戈麦斯网站开发

P3714 [BJOI2017]树的难题 求解树上长度在L到R的树链中颜色段权值和最大的链。 首先求解树上链的问题&#xff0c;而且限制了链的长度&#xff0c;那么我们需要点分治处理&#xff0c;然后考虑每次分治&#xff0c;我们可以把链分成两类&#xff0c;先处理同色连通块&#xf…

icp备案综合查询网站qq是哪家公司开发的软件

简介&#xff1a;Apache ECharts 是一款基于 Javascript 的数据可视化图表库&#xff0c;提供直观&#xff0c;生动&#xff0c;可交互&#xff0c;可个性化定制的数据可视化图表。 1、介绍 图 1.1 Apache ECharts 功能、运行环境 功能&#xff1a; ECharts&#xff…

两场div3 逆向思维

两场div3 逆向思维Posted on 2025-09-30 19:46 tttfred 阅读(0) 评论(0) 收藏 举报927div3 C 给你一个数列,和一个只含LR的操作序列s,若当前是L移除左端一个元素,若当前是R移除右端一个元素,问你每次所有元素…

详细介绍:(基于江协科技)51单片机入门:5.定时器

pre { white-space: pre !important; word-wrap: normal !important; overflow-x: auto !important; display: block !important; font-family: "Consolas", "Monaco", "Courier New", …

part2

T1很明显需要将 \(N\) 分解成 \(N = p_i ^ {Q_i}\)再很明显的是假如我们选了若干元素则满足条件的唯一性质为 \(\min(Q_{j,k}) = 0\) 且 \(\max(Q_{j,k}) = Q_k\) 最关键的也是这步容斥,我们用总数减去T2