public class BinaryTree { public Node root; public BinaryTree(Node root){ this.root = root; } public void insert(int x){ Node node = new Node(); node.key = x; Node current = root; Node parent = null; while(true){ parent = current; if(node.key < current.key){ //左孩子 current = current.left; if(current == null){ parent.left = node; return; } }else{ current = current.right; if(current == null){ parent.right = node; return; } } } } public void delete(Node node){ } public Node searche(Node node){ return null; } public void print(Node node){ if(node.left != null){ print(node.left); } System.out.println(node.key); if(node.right != null){ print(node.right); } } public static class Node { public int key ; public Node parent; public Node left; public Node right; public Node(int key){ this.key = key; } public Node(){}; public void insertReversion(Node node){ if(node.key < this.key){ if(this.left != null){ this.left.insertReversion(node); }else{ this.left = node; } }else{ if(this.right != null){ this.right.insertReversion(node); }else{ this.right = node; } } } } public static void main(String[] args) { BinaryTree bt = new BinaryTree(new Node()); bt.insert(32); bt.insert(5); bt.insert(74); bt.insert(345); bt.insert(4); bt.insert(34); bt.print(bt.root); System.out.println("*****************上面是用循环,下面使用递归**************"); Node rr = new Node(); Node a = new Node(7); Node b = new Node(23); Node c = new Node(56); Node d = new Node(3); rr.insertReversion(a); rr.insertReversion(b); rr.insertReversion(d); rr.insertReversion(c); bt.print(rr); }}