leetcode二叉树相关模板

复制代码
package com.leetcode102;

import java.util.List;

public class Main {
    public static void main(String[] args) {
        Integer[] arr = {3, 9, 20, null, null, 15, 7};
        TreeNode tree = createTree(arr, 0);
        printPreOrder(tree);
        System.out.println();
        printMidOrder(tree);
        System.out.println();
        printAfterOrder(tree);
        System.out.println();
    }

    /**
     * 前序遍历
     */
    public static void printPreOrder(TreeNode tree) {
        if (tree != null) {
            System.out.print(tree.val == null ? "" : tree.val + " ");
            printPreOrder(tree.left);
            printPreOrder(tree.right);
        }
    }

    /**
     * 中序遍历
     */
    public static void printMidOrder(TreeNode tree) {
        if (tree != null) {
            printMidOrder(tree.left);
            System.out.print(tree.val == null ? "" : tree.val + " ");
            printMidOrder(tree.right);
        }
    }

    /**
     * 后序遍历
     */
    public static void printAfterOrder(TreeNode tree) {
        if (tree != null) {
            printAfterOrder(tree.left);
            printAfterOrder(tree.right);
            System.out.print(tree.val == null ? "" : tree.val + " ");
        }
    }

    /**
     * 创建一个二叉树
     * ----3
     * -9     20
     * -----15  17
     */
    public static TreeNode createTree(Integer[] arr, int index) {

        TreeNode root = null;
        if (index < arr.length) {
            root = new TreeNode(arr[index]);
            root.left = createTree(arr, 2 * index + 1);
            root.right = createTree(arr, 2 * index + 2);
        }

        return root;
    }
}

class TreeNode {
    Integer val;
    TreeNode left;
    TreeNode right;

    TreeNode() {
    }

    TreeNode(Integer val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}
相关推荐
一 乐1 分钟前
校园二手交易|基于springboot + vue校园二手交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端
KIKIiiiiiiii2 分钟前
微信个人号API二次开发中的解决经验
java·人工智能·python·微信
梵刹古音3 分钟前
【C语言】 指针基础与定义
c语言·开发语言·算法
80530单词突击赢3 分钟前
SpringBoot整合SpringMVC全解析
java·spring boot·后端
vx1_Biye_Design13 分钟前
基于Spring Boot+Vue的学生管理系统设计与实现-计算机毕业设计源码46223
java·vue.js·spring boot·spring·eclipse·tomcat·maven
vx_Biye_Design14 分钟前
基于Spring Boot+vue的湖北旅游景点门票预约平台的设计--毕设附源码29593
java·vue.js·spring boot·spring cloud·servlet·eclipse·课程设计
啊阿狸不会拉杆20 分钟前
《机器学习导论》第 5 章-多元方法
人工智能·python·算法·机器学习·numpy·matplotlib·多元方法
hay_lee32 分钟前
Spring AI实现对话聊天-流式输出
java·人工智能·ollama·spring ai
Hx_Ma1638 分钟前
SpringBoot数据源自动管理
java·spring boot·spring
SunnyDays101139 分钟前
Java 高效实现 CSV 转 Excel
java·csv转excel