项目主页: https://github.com/gozhuyinglong/blog-demos
本文源码: https://github.com/gozhuyinglong/blog-demos/tree/main/java-data-structures
咱们前面讲到了数组和链表两种数据结构,其各自有本身的优缺点,咱们来回顾一下。java
优势:经过下标访问速度很是快。
缺点:须要检索具体某个值时,或者插入值时(会总体移动)效率较低node
优势:在插入某个值时,效率比数组高
缺点:检索某个值时效率仍然较低git
咱们本篇讲到的树,便能提升数据的存储和读取效率。github
树是一种非线性的数据结构,它包含n(n>=1)个节点,(n-1)条边的有穷集合。把它叫作“树”是由于它看起来像一个倒挂的树,也就是说它是根朝上,叶子朝下的。算法
结合上图了解树的经常使用术语,加深对树的理解。数组
树结构中的每个元素称为一个节点,如上图中的ABC......M数据结构
没有父节点的节点叫作根节点,如上图中的Aapp
一个节点的上级节点叫作它的父节点,一个节点最多只能有一个父节点,如上图中C是F的父节点ui
一个节点的下级节点叫作它的子节点,一个节点的子节点能够有多个,如上图中的IJK是E的子节点this
拥有相同父节点的节点叫作兄弟节点,如上图中的L和M是兄弟节点
没有子节点的节点叫作叶子节点,如图中的BFGLMIJK
父子节点间的链接称为边,一棵树的边数为(n-1)
节点上的元素值
从root节点找到该节点的路线,如上图中L的路径为A-D-H-L。路径的长为该路径上边的条数,L路径的长为3(n-1)。
距离根节点相等的路径长度为一层,如上图中A为第一层;BCDE为第二层;FGHIJK为第三层;LM为第四层
以某一节点(非root)作为根的树称为子树,如以E为根的树称为A的子树
树的最大层数,上图中树的高度为4
多棵子树构成树林
咱们将第3章中的树结构图经过Java代码进行实现。
TreeNode
类为树的一个节点,其中:
Tree
类实现了一棵树的初始化和遍历,listAll遍历算法的核心是递归。具体内容见代码
public class TreeDemo { public static void main(String[] args) { new Tree().initTree().listAll(); } private static class Tree { private TreeNode root; // 树根 /** * 初始化一棵树 */ private Tree initTree() { TreeNode a = new TreeNode("A"); TreeNode b = new TreeNode("B"); TreeNode c = new TreeNode("C"); TreeNode d = new TreeNode("D"); TreeNode e = new TreeNode("E"); TreeNode f = new TreeNode("F"); TreeNode g = new TreeNode("G"); TreeNode h = new TreeNode("H"); TreeNode i = new TreeNode("I"); TreeNode j = new TreeNode("J"); TreeNode k = new TreeNode("K"); TreeNode l = new TreeNode("L"); TreeNode m = new TreeNode("M"); root = a; a.firstChild = b; b.nextSibling = c; c.nextSibling = d; c.firstChild = f; d.nextSibling = e; d.firstChild = g; e.firstChild = i; g.nextSibling = h; h.firstChild = l; i.nextSibling = j; j.nextSibling = k; l.nextSibling = m; return this; } /** * 遍历一棵树,从root开始 */ public void listAll() { listAll(root, 0); } /** * 遍历一棵树 * * @param node 树节点 * @param depth 层级(用于辅助输出) */ public void listAll(TreeNode node, int depth) { StringBuilder t = new StringBuilder(); for (int i = 0; i < depth; i++) { t.append("\t"); } System.out.printf("%s%s\n", t.toString(), node.element); // 先遍历子节点,子节点的层级须要+1 if (node.firstChild != null) { listAll(node.firstChild, depth + 1); } // 后遍历兄弟节点,兄弟节点的层级不变 if (node.nextSibling != null) { listAll(node.nextSibling, depth); } } } private static class TreeNode { private final Object element; // 当前节点数据 private TreeNode firstChild; // 当前节点的第一个子节点 private TreeNode nextSibling; // 当前节点的下一个兄弟节点 public TreeNode(Object element) { this.element = element; } } }
输出结果:
A B C F D G H L M E I J K