二叉树的遍历总结

news2025/6/8 3:31:46
  • 144.二叉树的前序遍历(opens new window)
  • 145.二叉树的后序遍历(opens new window)
  • 94.二叉树的中序遍历

二叉数的先中后序统一遍历法

public static  void preOrder(BiTree root){
        BiTree p = root;
        LinkedList<BiTree> stack = new LinkedList<>();
        while(p != null || !stack.isEmpty()){
            if(p != null){
                System.out.print(p.val +"\t");
                stack.push(p);
                p = p.left;
            }else {
                p = stack.pop();
                p = p.right;
            }
        }
    }
public static  void preOrder00(BiTree root){
        LinkedList<BiTree>stack = new LinkedList<>();
        stack.push(root);
        while(!stack.isEmpty()){
            BiTree node = stack.peek();
            if(node != null){
                stack.pop();
                if(node.right != null){
                    stack.push(node.right);
                }
                if(node.left !=null){
                    stack.push(node.left);
                }
                stack.push(node);
                stack.push(null);
            }else {
                stack.pop();
                BiTree p = stack.peek();
                stack.pop();
                System.out.print(p.val + "\t");
            }
        }
        System.out.println();
    }
public  static void preOrder03(BiTree root){
        if(root == null){
            return;
        }
        LinkedList<BiTree> stack = new LinkedList<>();
        stack.push(root);
        Map<BiTree,Boolean> visited = new HashMap<>();
        while(!stack.isEmpty()){
            BiTree node = stack.peek();
            stack.pop();
            if(visited.getOrDefault(node,false)){
                System.out.print(node.val +"\t");
                continue;
            }
            if(node.right != null){
                stack.push(node.right);
                visited.put(node.right, false);
            }
            if(node.left != null){
                stack.push(node.left);
                visited.put(node.left,false);
            }
            stack.push(node);
            visited.put(node,true);
        }
        System.out.println("");
    }

 

public static  void inOrder(BiTree root){
        LinkedList<BiTree> stack = new LinkedList<>();
        BiTree p = root;
        while( p != null || !stack.isEmpty()){
            if(p != null){
                stack.push(p);
                p = p.left;
            }else {
                p = stack.pop();
                System.out.print(p.val + "\t");
                p = p.right;
            }
        }
    }
 public static void inOrder00(BiTree root){
        LinkedList<BiTree> stack = new LinkedList<BiTree>();
        stack.push(root);
        while(!stack.isEmpty()){
            BiTree node = stack.peek();
            if(node != null){
                stack.pop();
                if(node.right != null){
                    stack.push(node.right);
                }
                stack.push(node);
                stack.push(null);
                if(node.left != null){
                    stack.push(node.left);
                }
            }else {
                stack.pop();
                node = stack.peek();
                stack.pop();
                System.out.print(node.val + "\t");
            }
        }
        System.out.println();
    }
public static void inOrder03(BiTree root){
        LinkedList<BiTree> stack = new LinkedList<>();
        stack.push(root);
        Map<BiTree,Boolean> isVisited = new HashMap<BiTree,Boolean>();
        while(!stack.isEmpty()){
            BiTree node = stack.peek();
            stack.pop();
            if(isVisited.getOrDefault(node, false)){
                System.out.print(node.val +"\t");
                continue;
            }

            if(node.right != null){
                stack.push(node.right);
                isVisited.put(node.right, false);
            }

            stack.push(node);
            isVisited.put(node, false);

            if(node.left != null){
                stack.push(node.left);
                isVisited.put(node.left, false);
            }
            isVisited.put(node, true);
        }
    }

 

public static void postOrder00(BiTree root){
        LinkedList<BiTree> stack = new LinkedList<>();
        stack.push(root);
        while(!stack.isEmpty()){
            BiTree p = stack.peek();
            if(p != null){
                stack.pop();
                stack.push(p);
                stack.push(null);
                if(p.right != null){
                    stack.push(p.right);
                }
                if(p.left != null) {
                    stack.push(p.left);
                }
            }else {
                stack.pop();
                p = stack.peek();
                System.out.print(p.val +"\t");
                stack.pop();
            }
        }
        System.out.println();
    }
 public static void postOrder03(BiTree root){
        LinkedList<BiTree> stack = new LinkedList<>();
        BiTree p = root;
        stack.push(p);
        Map<BiTree,Boolean> isVisited = new HashMap<>();
        while(!stack.isEmpty()){
            BiTree node = stack.peek();
            stack.pop();
            if(isVisited.getOrDefault(node,false)){
                System.out.print(node.val+"\t");
                continue;
            }
            stack.push(node);
            isVisited.put(node, true);

            if(node.right != null){
                stack.push(node.right);
                isVisited.put(node.right, false);
            }

            if(node.left != null){
                stack.push(node.left);
                isVisited.put(node.left, false);
            }
        }
    }
public static  void postOrder(BiTree root){
        LinkedList<BiTree> stack = new LinkedList<BiTree>();
        BiTree p = root;
        BiTree r = null;
        while(p != null || !stack.isEmpty()){
            if(p != null){
                stack.push(p);
                p = p.left;
            }else {
                p = stack.peek();
                if (p.right != null && p.right != r) {
                    p = p.right;
                } else {
                    p = stack.pop();
                    System.out.print(p.val + "\t");
                    r = p;
                    p = null;
                }
            }
        }
    }

107.二叉树的层次遍历 II

力扣题目链接(opens new window)

给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

107.二叉树的层次遍历II

 

 

public List<List<Integer>> levelOrderBottom(TreeNode root) {
        List<List<Integer>> results = new ArrayList<List<Integer>>();
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        if(root == null){
            return results;
        }
        queue.offer(root);
        while(!queue.isEmpty()){
            int queueSize = queue.size();
            List<Integer> result = new ArrayList<Integer>();
            for(int i = 1; i <= queueSize; i++){
                TreeNode node = queue.poll();
                result.add(node.val);
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
                if(i == queueSize){
                    results.addFirst(result);
                }
            }
        }
       return results;
    }

199.二叉树的右视图

力扣题目链接(opens new window)

给定一棵二叉树,想象自己站在它的右侧,按照从顶部到底部的顺序,返回从右侧所能看到的节点值。

199.二叉树的右视图

public List<Integer> rightSideView(TreeNode root) {
        List<Integer> results=  new ArrayList<Integer>();
        if(root == null){
            return results;
        }
        Queue<TreeNode> queue  = new LinkedList<TreeNode>();
        queue.offer(root);
        while(!queue.isEmpty()){
            int queueSize = queue.size();
            for(int i = 1; i <= queueSize; i++){
                TreeNode node = queue.poll();
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
                if(i == queueSize){
                    results.add(node.val);
                }
            }
        }
        return results;
    }

429.N叉树的层序遍历

力扣题目链接(opens new window)

给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。

例如,给定一个 3叉树 :

429. N叉树的层序遍历

返回其层序遍历:

[ [1], [3,2,4], [5,6] ]

public List<List<Integer>> levelOrder(Node root) {
        LinkedList<Node> queue = new LinkedList<Node>();
        queue.offer(root);
        List<List<Integer>> results = new ArrayList<List<Integer>>();
        if(root == null){
            return results;
        }
        while(!queue.isEmpty()){
            List<Integer> result = new ArrayList<Integer>();
            int levelSize = queue.size();
            for(int i = 1; i <= levelSize; i++){
                Node node = queue.poll();
                result.add(node.val);
                if(node.children != null){
                    for(int j = 0; j < node.children.size();j++){
                        queue.offer(node.children.get(j));
                    }
                }
            }
            results.add(result);
        }
        return results;
    }

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

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

相关文章

win32相关(远程线程和远程线程注入)

远程线程和远程线程注入 CreateRemoteThread函数 作用&#xff1a;创建在另一个进程的虚拟地址空间中运行的线程 HANDLE CreateRemoteThread([in] HANDLE hProcess, // 需要在哪个进程中创建线程[in] LPSECURITY_ATTRIBUTES lpThreadAttributes, // 安全…

[Spring]-AOP

AOP场景 AOP: Aspect Oriented Programming (面向切面编程) OOP: Object Oriented Programming (面向对象编程) 场景设计 设计: 编写一个计算器接口和实现类&#xff0c;提供加减乘除四则运算 需求: 在加减乘除运算的时候需要记录操作日志(运算前参数、运算后结果)实现方案:…

agent 开发

什么是 agent&#xff1f; Agent智能体&#xff08;又称AI Agent&#xff09;是一种具备自主感知、决策与行动能力的智能系统&#xff0c;其核心在于模仿人类的认知过程来处理复杂任务。以下是其关键特性和发展现状的综合分析&#xff1a; 一、核心定义与特征 #‌## 自主决策…

Golang——5、函数详解、time包及日期函数

函数详解、time包及日期函数 1、函数1.1、函数定义1.2、函数参数1.3、函数返回值1.4、函数类型与变量1.5、函数作参数和返回值1.6、匿名函数、函数递归和闭包1.7、defer语句1.8、panic和recover 2、time包以及日期函数2.1、time.Now()获取当前时间2.2、Format方法格式化输出日期…

深度学习环境配置指南:基于Anaconda与PyCharm的全流程操作

一、环境搭建前的准备 1. 查看基础环境位置 conda env list 操作说明&#xff1a;通过该命令确认Anaconda默认环境&#xff08;base&#xff09;所在磁盘路径&#xff08;如D盘&#xff09;&#xff0c;后续操作需跳转至该磁盘根目录。 二、创建与激活独立虚拟环境 1. 创…

打卡day46

知识点回顾&#xff1a; 不同CNN层的特征图&#xff1a;不同通道的特征图什么是注意力&#xff1a;注意力家族&#xff0c;类似于动物园&#xff0c;都是不同的模块&#xff0c;好不好试了才知道。通道注意力&#xff1a;模型的定义和插入的位置通道注意力后的特征图和热力图 内…

在SpringBoot中使用AWS SDK实现邮箱验证码服务

1.依赖导入&#xff08;maven&#xff09; <dependency><groupId>software.amazon.awssdk</groupId><artifactId>ses</artifactId><version>2.31.46</version></dependency> 2.申请两个key 发件人邮箱需要验证&#xff1a; …

深入理解二叉搜索树:原理到实践

1.二叉搜索树的概念 ⼆叉搜索树⼜称⼆叉排序树&#xff0c;它或者是⼀棵空树&#xff0c;或者是具有以下性质的⼆叉树 若它的左树不为空&#xff0c;则左子树上所有节点的值都小于或等于根节点的值。若它的右树不为空&#xff0c;则右子树上所有节点的值都大于或等于根节点的…

测试W5500的第11步_使用ARP解析IP地址对应的MAC地址

本文介绍了基于W5500芯片的ARP协议实现方法&#xff0c;详细阐述了ARP请求与回复的工作机制。ARP协议通过广播请求和单播回复实现IP地址与MAC地址的映射&#xff0c;确保局域网设备间的可靠通信。文章提供了完整的STM32F10x开发环境下的代码实现&#xff0c;包括网络初始化、SP…

终极数据结构详解:从理论到实践

终极数据结构详解&#xff1a;从理论到实践 我将从 底层原理、时间复杂度、空间优化、实际应用 和 代码实现 五个维度&#xff0c;彻底解析数据结构。内容涵盖&#xff1a; 线性结构&#xff08;数组、链表、栈、队列&#xff09;非线性结构&#xff08;树、图&#xff09;高…

【k8s】k8s集群搭建

k8s集群搭建 一、环境准备1.1 集群类型1.2 安装方式1.3 主机规划1.4 环境配置1.4.1 说明1.4.2 初始化1.4.3 关闭防火墙和禁止防火墙开机启动1.4.4 设置主机名1.4.5 主机名解析1.4.6 时间同步1.4.7 关闭selinux1.4.8 关闭swap分区1.4.9 将桥接的IPv4流量传递到iptables的链1.4.1…

60天python训练计划----day45

DAY 45 Tensorboard使用介绍 知识点回顾&#xff1a; tensorboard的发展历史和原理tensorboard的常见操作tensorboard在cifar上的实战&#xff1a;MLP和CNN模型 之前的内容中&#xff0c;我们在神经网络训练中&#xff0c;为了帮助自己理解&#xff0c;借用了很多的组件&#x…

C# Wkhtmltopdf HTML转PDF碰到的问题

最近碰到一个Html转PDF的需求&#xff0c;看了一下基本上都是需要依赖Wkhtmltopdf&#xff0c;需要在Windows或者linux安装这个可以后使用。找了一下选择了HtmlToPDFCore&#xff0c;这个库是对Wkhtmltopdf.NetCore简单二次封装&#xff0c;这个库的好处就是通过NuGet安装HtmlT…

Vue3 (数组push数据报错) 解决Cannot read property ‘push‘ of null报错问题

解决Cannot read property ‘push‘ of null报错问题 错误写法 定义变量 <script setup>const workList ref([{name:,value:}])</script>正确定义变量 <script setup>const workList ref([]) </script>解决咯~

html文字红色粗体,闪烁渐变动画效果,中英文切换版本

1. 代码 <!DOCTYPE html> <html lang"zh"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>红色粗体闪烁文字表格 - 中英文切换</t…

基于Django开发的运动商城系统项目

运动商城系统项目描述 运动商城系统是一个基于现代Web技术构建的电子商务平台&#xff0c;专注于运动类商品的在线销售与管理。该系统采用前后端分离架构&#xff0c;前端使用Vue.js实现动态交互界面&#xff0c;后端基于Django框架提供RESTful API支持&#xff0c;数据库采用…

Python60日基础学习打卡Day45

之前的神经网络训练中&#xff0c;为了帮助理解借用了很多的组件&#xff0c;比如训练进度条、可视化的loss下降曲线、权重分布图&#xff0c;运行结束后还可以查看单张图的推理效果。 如果现在有一个交互工具可以很简单的通过按钮完成这些辅助功能那就好了&#xff0c;他就是…

【Visual Studio 2022】卸载安装,ASP.NET

Visual Studio 2022 彻底卸载教程 手动清理残留文件夹 删除C:\Program Files\Microsoft Visual Studio 是旧版本 Visual Studio 的残留安装目录 文件夹名对应的 Visual Studio 版本Microsoft Visual Studio 9.0Visual Studio 2008Microsoft Visual Studio 10.0Visual Studio…

thinkphp-queue队列随笔

安装 # 创建项目 composer create-project topthink/think 5.0.*# 安装队列扩展 composer require topthink/think-queue 配置 // application/extra/queue.php<?php return [connector > Redis, // Redis 驱动expire > 0, // 任务的过期时间…

STM32标准库-TIM输出比较

文章目录 一、输出比较二、PWM2.1简介2.2输出比较通道&#xff08;高级&#xff09;2.3 输出比较通道&#xff08;通用&#xff09;2.4输出比较模式2.5 PWM基本结构1、时基单元2、输出比较单元3、输出控制&#xff08;绿色右侧&#xff09;4、右上波形图&#xff08;以绿色脉冲…