Add a chapter of binary tree.

This commit is contained in:
krahets
2022-11-12 22:48:46 +08:00
parent ac8d0bcfeb
commit 7fdb4d1443
11 changed files with 150 additions and 10 deletions

View File

@@ -0,0 +1,34 @@
package chapter_tree;
import include.*;
public class binary_tree {
public static void main(String[] args) {
/* 初始化二叉树 */
// 初始化结点
TreeNode n1 = new TreeNode(1);
TreeNode n2 = new TreeNode(2);
TreeNode n3 = new TreeNode(3);
TreeNode n4 = new TreeNode(4);
TreeNode n5 = new TreeNode(5);
// 构建引用指向(即指针)
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
System.out.println("\n初始化二叉树\n");
PrintUtil.printTree(n1);
/* 插入与删除结点 */
TreeNode P = new TreeNode(0);
// 在 n1 -> n2 中间插入结点 P
n1.left = P;
P.left = n2;
System.out.println("\n插入结点 P 后\n");
PrintUtil.printTree(n1);
// 删除结点 P
n1.left = n2;
System.out.println("\n删除结点 P 后\n");
PrintUtil.printTree(n1);
}
}

View File

@@ -0,0 +1,36 @@
package chapter_tree;
import include.*;
import java.util.*;
public class binary_tree_bfs {
/* 层序遍历 */
static List<Integer> hierOrder(TreeNode root) {
// 初始化队列,加入根结点
Queue<TreeNode> queue = new LinkedList<>() {{ add(root); }};
// 初始化一个列表,用于保存遍历序列
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
TreeNode node = queue.poll(); // 队列出队
list.add(node.val); // 保存结点
if (node.left != null)
queue.offer(node.left); // 左子结点入队
if (node.right != null)
queue.offer(node.right); // 右子结点入队
}
return list;
}
public static void main(String[] args) {
/* 初始化二叉树 */
// 这里借助了一个从数组直接生成二叉树的函数
TreeNode root = TreeNode.arrToTree(new Integer[] {
1, 2, 3, 4, 5, 6, 7, null, null, null, null, null, null, null, null });
System.out.println("\n初始化二叉树\n");
PrintUtil.printTree(root);
/* 层序遍历 */
List<Integer> list = hierOrder(root);
System.out.println("\n层序遍历的结点打印序列 = " + list);
}
}

View File

@@ -0,0 +1,60 @@
package chapter_tree;
import include.*;
import java.util.*;
public class binary_tree_dfs {
// 初始化列表,用于存储遍历序列
static ArrayList<Integer> list = new ArrayList<>();
/* 前序遍历 */
static void preOrder(TreeNode root) {
if (root == null) return;
// 访问优先级:根结点 -> 左子树 -> 右子树
list.add(root.val);
preOrder(root.left);
preOrder(root.right);
}
/* 中序遍历 */
static void inOrder(TreeNode root) {
if (root == null) return;
// 访问优先级:左子树 -> 根结点 -> 右子树
inOrder(root.left);
list.add(root.val);
inOrder(root.right);
}
/* 后序遍历 */
static void postOrder(TreeNode root) {
if (root == null) return;
// 访问优先级:左子树 -> 右子树 -> 根结点
postOrder(root.left);
postOrder(root.right);
list.add(root.val);
}
public static void main(String[] args) {
/* 初始化二叉树 */
// 这里借助了一个从数组直接生成二叉树的函数
TreeNode root = TreeNode.arrToTree(new Integer[] {
1, 2, 3, 4, 5, 6, 7, null, null, null, null, null, null, null, null});
System.out.println("\n初始化二叉树\n");
PrintUtil.printTree(root);
/* 前序遍历 */
list.clear();
preOrder(root);
System.out.println("\n前序遍历的结点打印序列 = " + list);
/* 中序遍历 */
list.clear();
inOrder(root);
System.out.println("\n中序遍历的结点打印序列 = " + list);
/* 后序遍历 */
list.clear();
postOrder(root);
System.out.println("\n后序遍历的结点打印序列 = " + list);
}
}