二叉查找树
二叉查找树(binary search tree),二叉查找树在二叉树的基础上增加了以下几个条件:
如果左子树不为空,则左子树上所有节点的值均小于根节点的值
如果右子树不为空,则右子树上所有节点的值均大于根节点的值
左、右子树也都是二叉查找树。
二查查找树的时间复杂度是O(log(n)),但是极端情况会退化成O(n)
package tree; /** * @author: tianhaichao * @date: 2022/8/29 14:21 * @description: 二叉树 有序插入,中序遍历 */ public class BinaryTree { private static TreeNode root; public static void insertNode(int data) { if (root == null) { root = new TreeNode(data); return; } else { insertNode(root, data); } } /** * @author: tianhaichao * @date: 2022/9/20 10:14 * @description:插入数据 */ public static void insertNode(TreeNode node, int data) { // 如果比当前节点大,放右边 if (data > node.getData()) { // 如果右节点为空,赋值 if (node.getRightNode() == null) { node.setRightNode(new TreeNode(data)); return; } else { insertNode(node.getRightNode(), data); } } // 如果比当前节点小,放左边 if (data <= node.getData()) { if (node.getLeftNode() == null) { node.setLeftNode(new TreeNode(data)); return; } else { insertNode(node.getLeftNode(), data); } } } /** * @author: tianhaichao * @date: 2022/9/20 15:10 * @description:前序遍历 */ public static void prepTraversal(TreeNode node) { if (node == null) { return; } // 先输出父节点,再输出左节点和右节点 System.out.print(node.getData() + " "); prepTraversal(node.getLeftNode()); prepTraversal(node.getRightNode()); } public static void main(String[] args) { BinaryTree.insertNode(3); BinaryTree.insertNode(10); BinaryTree.insertNode(5); BinaryTree.insertNode(6); BinaryTree.insertNode(8); BinaryTree.prepTraversal(root); } } class TreeNode { private int data; private TreeNode leftNode; private TreeNode rightNode; public TreeNode(int data) { this.data = data; } public TreeNode(int data, TreeNode leftNode, TreeNode rightNode) { this.data = data; this.leftNode = leftNode; this.rightNode = rightNode; } public int getData() { return data; } public void setData(int data) { this.data = data; } public TreeNode getLeftNode() { return leftNode; } public void setLeftNode(TreeNode leftNode) { this.leftNode = leftNode; } public TreeNode getRightNode() { return rightNode; } public void setRightNode(TreeNode rightNode) { this.rightNode = rightNode; } }