树的基本概念
树是一种非常有用的数据结构,数据库的实现大部分都是基于树结构的,比如在一种特殊的树结构“红黑树”中,寻找任意元素的复杂度仅仅只需要log(N)。树是一种由节点组成的数据结构,但它比链表更加高级,在链表中,一个节点连接着另一个节点,树也是由许多的节点构成的,唯一的区别就是一个树节点可以连接多个树节点,一颗树只有一个根节点,根节点作为起源,由它展开一个树状的数据结构。
在实现树之前,我们来了解一下树的基本定义:
在树中,每个节点都含有自己的数值,以及与之相连的子节点,连接节点的线叫做相连线(edge)。如下图所示,A是根节点(root),也是B和C的父节点(parent node),也就是说B、C都是A的子节点(child node)。同理,B是D和E的父节点,以此类推。要注意H、I、J、F、G都是尾节点(leaf node),因为它们位于树的最底部,没有任何子节点。
一个树由许许多多的子树(sub-tree)构成,每个节点加上它所有的子节点(包括子节点的子节点们)就是一个子树,如上图,D、H、和I就是能构成sub tree,B、D、E、H、I、和J也是一个子树。
树中还有两个重要的名词要记住,一个是节点的高度(height),意味着此节点到尾节点之间相连线的数量,B的高度就是2,因为B到尾节点H之间的edge数量为2。另一个名词就是节点的深度(depth),意味着此节点到根节点的edge数量,D的深度是2,因为D到根节点A之间的edge数量是2。
树的种类
树的种类有很多,其中排序二叉树会是我们的重点,在后面也会学习如何用Java将其实现,至于其他的树类型,大家目前只要大概理解就好:
- 二叉树(Binary Tree):每个节点最多含有两个子节点,上面图示中的树就是二叉树。
- 完全二叉树(Complete Binary Tree):假设一个二叉树深度(depth)为d(d > 1),除了第d层外,其它各层的节点数量均已达到最大值,且第d层所有节点从左向右紧密排列,这样的二叉树就是完全二叉树。
- 满二叉树(Full Binary Tee):在满二叉树中,每个不是尾节点的节点都有两个子节点。
- 排序二叉树(Binary Search Tree):在此树中,每个节点的数值比左子树上的每个节点都大,比所有右子树上的节点都小。
- 平衡二叉树(AVL Tree):任何节点的两颗子树的高度差不大于1的二叉树。
- B树(B-Tree):B树和平衡二插树一样,只不过它是一种多叉树(一个节点的子节点数量可以超过二)。
- 红黑树(Red—Black Tree):是一种自平衡二叉寻找树。
二分查找树(Binary Search Tree)的实现
接下来,我们就来实现二分查找树(Binary Search Tree),也叫做排序二叉树。在这种树中,我们寻找一个特定的数值非常容易,因为二分查找树满足以下的特性:每个节点都比自己左子树上的节点大,并比右子树上的节点小。如果我们想要寻找一个特定的元素,只需要依赖其特性,顺着特定的路径就能找到目标。
在此树中,搜索、插入和删除的复杂度等于树高,往往就是O(logN),非常合适用来存储数据。接下来我们就使用Java来实现这个数据结构,首先我们定义好树和节点:
public class BST { static class TreeNode { public int value; public TreeNode left; public TreeNode right; public TreeNode(int value) { this.value = value; } } private TreeNode root; }
TreeNode就是我们的树节点,其中包含value记录数值,left指向left child,right指向right child。BST就是二分查找树,其中只需要记录根节点root即可。下面是核心方法 insert 的实现:
public void insert(int key) { if(root == null) { root = new TreeNode(key); return; } TreeNode current = root; TreeNode parent = null; while(true) { parent = current; if(key < parent.value) { current = parent.left; if(current == null) { parent.left = new TreeNode(key); return; } } else if (key > parent.value){ current = parent.right; if(current == null) { parent.right = new TreeNode(key); return; } } else { return; // BST does not allow nodes with the same value } } }
在insert中,我们用current来寻找要插入的位置,通过比较数值大小不断地迭代遍历左子树或右子树以找到合适的位置。get的逻辑很简单,只需要比对数值大小遍历左右子树即可:
public TreeNode get(int key) { TreeNode current = root; while(current != null && current.value != key) { if (key < current.value) { current = current.left; } else if (key > current.value) { current =current.right; } } return current == null ? null : current; }
delete比较复杂,我们需要考虑被删除节点的属性进行不同的逻辑操作,在下面的代码中,我们根据三种不同情况对树进行不同的操作(被删节点是尾节点;被删节点只有一个孩子;被删节点有两个孩子):
public boolean delete(int key) { TreeNode parent = root; TreeNode current = root; boolean isLeftChild = false; while(current != null && current.value != key) { parent = current; if(current.value > key) { isLeftChild = true; current = current.left; } else { isLeftChild = false; current = current.right; } } if(current == null) { return false; } // Case 1: if node to be deleted has no children if(current.left == null && current.right == null) { if(current == root) { root = null; } else if(isLeftChild) { parent.left = null; } else { parent.right = null; } // Case 2: if node to be deleted has only one child } else if (current.right == null) { if(current == root) { root = current.left; } else if (isLeftChild) { parent.left = current.left; } else { parent.right = current.left; } } else if (current.left == null) { if(current == root) { root = current.right; } else if (isLeftChild) { parent.left = current.right; } else { parent.right = current.right; } // Case 3: current.left != null && current.right != null } else { TreeNode successor = getSuccessor(current); if (current == root) { root = successor; } else if (isLeftChild) { parent.left = successor; } else { parent.right = successor; } successor.left = current.left; } return true; } private TreeNode getSuccessor(TreeNode node) { TreeNode successor = null; TreeNode successorParent = null; TreeNode current = node.right; while (current != null) { successorParent = successor; successor = current; current = current.left; } if (successor != node.right) { successorParent.left= successor.right; successor.right = node.right; } return successor; }
如果看完代码还不理解的朋友可以查看我的教学视频,以上就是二分查找树的实现,下面我们来聊聊遍历树的不同方法。
树的遍历 Tree Traversal
不像数组,在树中我们无法随时获取任意节点,遍历树总是从根节点开始,以下我们就来实现常见的三种遍历树的方式:
- 前序遍历 (Pre-order Traversal)
- 中序遍历 (In-order Traversal)
- 后序遍历 (Post-order Traversal)
前序遍历 Preorder Traversal
在前序遍历中,先访问节点自己,然后访问左子树,最后再访问右子树,对于每个节点迭代此操作:
public static void preOrderTraversal(TreeNode root) { if(root == null) { return; } System.out.println(root.value); preOrderTraversal(root.left); preOrderTraversal(root.right); }
中序遍历 Inorder Traversal
在中序遍历中,先访问左子树上的节点,再访问自己,最后再访问右子树上的节点:
public static void inOrderTraversal(TreeNode root) { if(root == null) { return; } inOrderTraversal(root.left); System.out.println(root.value); inOrderTraversal(root.right); }
后序遍历 Postorder Traversal
在后序遍历中,先访问左右子树,最后再访问自己:
public static void postOrderTraversal(TreeNode root) { if(root == null) { return; } postOrderTraversal(root.left); postOrderTraversal(root.right); System.out.println(root.value); }
如果使用中序遍历二分查找树,我们得到的结果就会是排好序的数值。以上就是树的基础概念,下一章我们会讲解用于排序的两种数据结构:优先队列和堆,其中堆也是一种特殊的树结构。
LeetCode题目和源代码
LeetCode题目
- Check Completeness of a Binary Tree (958)
- Balanced Binary Tree (110)
- Symmetric Tree (101)
- Insert into a Binary Search Tree (701)
- Maximum Depth of Binary Tree (104)
源代码