
package com.atguigu.binarysorttree;/** * 二叉排序树 * * @author Dxkstart * @create 2022-04-10-15:48 */public class BinarySortTreeDemo { public static void main(String[] args) { int[] arr = new int[]{7,3,10,12,5,1,9}; BinarySortTree binarySortTree = new BinarySortTree(); // 向树中添加 for (int i = 0; i < arr.length; i++) { binarySortTree.add(new Node(arr[i])); } // 遍历 binarySortTree.infixOrder(); }}// 创建二叉排序树class BinarySortTree { private Node root; // 添加节点的方法 public void add(Node node) { // 如果是空树 if (root == null) { root = node; } else { root.add(node); } } // 中序遍历 public void infixOrder() { if (root != null) { root.infixOrder(); }else { System.out.println("此二叉排序树为空"); } }}class Node { int value; Node left; Node right; public Node(int value) { this.value = value; } // 添加节点的方法 public void add(Node node) { if (node == null) { return; } // 判断传入的节点的值,和当前子树的根节点的值的关系 if (node.value < this.value) { // 如果当前节点的左节点为空 if (this.left == null) { // 直接将该节点挂在this节点的左边 this.left = node; return; } else { // 继续向左递归 this.left.add(node); } // 当前节点大于this节点的值 } else if (node.value > this.value) { // 如果this节点的右节点为空 if (this.right == null) { // 直接将该节点挂在this节点的右边 this.right = node; return; } else { //继续向右递归 this.right.add(node); } } } // 中序遍历 public void infixOrder() { if (this.left != null) { // 向左递归 this.left.infixOrder(); } // 中间节点 System.out.println(this.value); if (this.right != null) { // 向右递归 this.right.infixOrder(); } } @Override public String toString() { return "Node{" + "value=" + value + '}'; }}
