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;
}
}
leetcode二叉树相关模板
Pastthewind2023-10-27 8:43
相关推荐
Mahir081 小时前
Spring 循环依赖深度解密:从问题本质到三级缓存源码级解析RyFit2 小时前
SpringAI 常见问题及解决方案大全石山代码2 小时前
C++ 内存分区 堆区心中有国也有家2 小时前
cann-recipes-infer:昇腾 NPU 推理的“菜谱集合”绝知此事3 小时前
【算法突围 01】线性结构与哈希表:后端开发的收纳术无风听海3 小时前
C# 隐式转换深度解析碧海银沙音频科技研究院3 小时前
通话AEC与语音识别AEC的软硬回采链路一只大袋鼠3 小时前
Git 进阶(二):分支管理、暂存栈、远程仓库与多人协作csdn_aspnet3 小时前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯