12.28

二叉树的遍历(前序,中序,后序)

思路

递归是二叉树遍历情况下思路有点绕,但是代码最简洁的一种。

总结

简单熟悉了下语法。

递归三要素:

  1. 确定递归函数的参数和返回值: 确定哪些参数是递归的过程中需要处理的,那么就在递归函数里加上这个参数, 并且还要明确每次递归的返回值是什么进而确定递归函数的返回类型。
  2. 确定终止条件: 写完了递归算法, 运行的时候,经常会遇到栈溢出的错误,就是没写终止条件或者终止条件写的不对,操作系统也是用一个栈的结构来保存每一层递归的信息,如果递归没有终止,操作系统的内存栈必然就会溢出。
  3. 确定单层递归的逻辑: 确定每一层递归需要处理的信息。在这里也就会重复调用自己来实现递归的过程。

代码

java 复制代码
    //前序
    public static List<Integer> preorderTraversal(TreeNode root){
        List<Integer> res=new ArrayList<>();
        preorder(root,res);
        return res;
    }

    public static void preorder(TreeNode root,List<Integer> res){
        if (root!=null){
            res.add(root.val);
            preorder(root.left,res);
            preorder(root.right,res);
        }
    }


    //中序
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res=new ArrayList<>();
        postorder(root,res);
        return res;
    }
    public void postorder(TreeNode root,List<Integer> res){
        if (root!=null){
            postorder(root.left,res);
            postorder(root.right,res);
            res.add(root.val);
        }
    }

    //后序
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res=new ArrayList<>();
        inorder(root,res);
        return res;

    }
    public void inorder(TreeNode root,List<Integer> res){
        if (root!=null){
            inorder(root.left,res);
            res.add(root.val);
            inorder(root.right,res);

        }
    }
相关推荐
努力写代码的熊大13 分钟前
c++异常和智能指针
java·开发语言·c++
山岚的运维笔记17 分钟前
SQL Server笔记 -- 第15章:INSERT INTO
java·数据库·笔记·sql·microsoft·sqlserver
Yvonne爱编码17 分钟前
JAVA数据结构 DAY5-LinkedList
java·开发语言·python
小王不爱笑1321 小时前
LangChain4J 整合多 AI 模型核心实现步骤
java·人工智能·spring boot
西凉的悲伤1 小时前
spring-boot-starter-validation使用注解进行参数校验
java·spring boot·参数校验·validation·注解校验参数
LucDelton1 小时前
Java 读取无限量文件读取的思路
java·运维·网络
夹锌饼干1 小时前
mysql死锁排查流程--(处理mysql阻塞问题)
java·mysql
小信丶1 小时前
@EnableTransactionManagement注解介绍、应用场景和示例代码
java·spring boot·后端
To Be Clean Coder1 小时前
【Spring源码】createBean如何寻找构造器(四)——类型转换与匹配权重
java·后端·spring
-孤存-2 小时前
SpringBoot核心注解与配置详解
java·spring boot·后端