每个节点最多有两个子节点,分别为左子节点和右子节点。
每个节点都有一个父节点,除了根节点。
二叉树的每个节点可以包含一些数据或值。
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
class TreeNode {
Integer val;
TreeNode left, right;
public TreeNode(Integer val) {
this.val = val;
}
}
public class Test2 {
public static void main(String[] args) {
// 构建二叉树
TreeNode root = new TreeNode(11);
root.left = new TreeNode(8);
root.right = new TreeNode(16);
root.left.left = new TreeNode(5);
root.left.right = new TreeNode(10);
root.right.right = new TreeNode(18);
dlr(root);
System.out.println();
ldr(root);
System.out.println();
lrd(root);
System.out.println();
bfs(root);
}
/**
* 先根遍历 : 11 8 5 10 16 18
*
* @param root
*/
private static void dlr(TreeNode root) {
// 二叉树的先根遍历
if (root != null) {
System.out.print(root.val + " ");
dlr(root.left);
dlr(root.right);
}
}
/**
* 中根遍历 : 5 8 10 11 16 18
*
* @param root
*/
private static void ldr(TreeNode root) {
// 二叉树的先根遍历
if (root != null) {
ldr(root.left);
System.out.print(root.val + " ");
ldr(root.right);
}
}
/**
* 后根遍历 : 5 10 8 18 16 11
*
* @param root
*/
private static void lrd(TreeNode root) {
// 二叉树的先根遍历
if (root != null) {
lrd(root.left);
lrd(root.right);
System.out.print(root.val + " ");
}
}
/**
* 广度优先遍历BFS : 11 8 16 5 10 18
*
* @param root
*/
private static void bfs(TreeNode root) {
Queue<TreeNode> queue = new ArrayBlockingQueue<>(10);
if (root == null) {
return;
}
queue.add(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
System.out.print(node.val + " ");
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
}
}
👋 你好,我是 Lorin 洛林,一位 Java 后端技术开发者!座右铭:Technology has the power to make the world a better place.
🚀 我对技术的热情是我不断学习和分享的动力。我的博客是一个关于Java生态系统、后端开发和最新技术趋势的地方。
🧠 作为一个 Java 后端技术爱好者,我不仅热衷于探索语言的新特性和技术的深度,还热衷于分享我的见解和最佳实践。我相信知识的分享和社区合作可以帮助我们共同成长。
💡 在我的博客上,你将找到关于Java核心概念、JVM 底层技术、常用框架如Spring和Mybatis 、MySQL等数据库管理、RabbitMQ、Rocketmq等消息中间件、性能优化等内容的深入文章。我也将分享一些编程技巧和解决问题的方法,以帮助你更好地掌握Java编程。
🌐 我鼓励互动和建立社区,因此请留下你的问题、建议或主题请求,让我知道你感兴趣的内容。此外,我将分享最新的互联网和技术资讯,以确保你与技术世界的最新发展保持联系。我期待与你一起在技术之路上前进,一起探讨技术世界的无限可能性。
📖 保持关注我的博客,让我们共同追求技术卓越。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。