二叉搜索树
我们可以用二叉搜索树中的插入操作构建一棵二叉搜索树
二叉搜索树的伪代码:
Java实现:
public class BSTree { Node<Integer> root = new Node<Integer>(); public BSTree(){ this.root = null; } //插入 public Node<Integer> insert (int key) { Node<Integer> newNode = new Node<>(key); Node<Integer> current = root; Node<Integer> parent = null; if (current == null) { root = newNode; return newNode; } while (true) { parent = current; if (key < current.data) { current = current.left; if (current == null) { parent.left = newNode; return newNode; } } else { current = current.right; if (current == null) { parent.right = newNode; return newNode; } } } } //前序遍历 public void PreOrder(Node node) { if (node != null) { System.out.print(node.data + " "); PreOrder(node.left); PreOrder(node.right); } } }
我们实现一棵这样的BST
测试类:
public class BSTreeTest { public static void main(String[] args) { BSTree tree =new BSTree(); tree.insert(30); tree.insert(15); tree.insert(41); tree.insert(35); tree.insert(50); tree.PreOrder(tree.root); } }
结果:
30 15 41 35 30 50