二叉排序樹又稱二叉查找樹。它或者是一顆空樹,或者是具有如下性質的二叉樹:
1.如果左子樹不空,那么左子樹上的所有節點均小於它的根節點的值;
2.如果右子樹不空,那么右子樹上的所有節點均大於它的根節點的值;
3.左右字樹也分別是二叉排序樹。
關於二叉排序樹的建立和遍歷的代碼實現如下:
1 class Node{ 2 public int data; 3 public Node left; 4 public Node right; 5 public Node(int data){ 6 this.data = data; 7 this.left = null; 8 this.right = null; 9 } 10 } 11 12 public class BinaryTree{ 13 14 private Node root; 15 public BinaryTree(){ 16 root = null; 17 } 18 19 //將date插入到排序二叉樹中 20 public void insert(int data){ 21 Node newNode = new Node(data); 22 if(root == null) 23 root = newNode; 24 else{ 25 Node current = root; 26 Node parent; 27 while (true) { //尋找插入的位置 28 parent = current; 29 if(data < current.data){ 30 current = current.left; 31 if(current == null){ 32 parent.left = newNode; 33 return; 34 } 35 } 36 else{ 37 current = current.right; 38 if(current == null){ 39 parent.right = newNode; 40 return; 41 } 42 } 43 } 44 } 45 } 46 //輸入數值,構建二叉樹 47 public void buildTree(int[] data){ 48 for (int i = 0; i<data.length; i++) { 49 insert(data[i]); 50 } 51 } 52 //中序遍歷方法遞歸實現 53 public void inOrder(Node localRoot){ 54 if (localRoot != null) { 55 inOrder(localRoot.left); 56 System.out.print(localRoot.data + " "); 57 inOrder(localRoot.right); 58 } 59 } 60 public void inOrder(){ 61 this.inOrder(this.root); 62 } 63 //先序遍歷方法遞歸實現 64 public void preOrder(Node localRoot){ 65 if (localRoot != null) { 66 System.out.print(localRoot.data + " "); 67 preOrder(localRoot.left); 68 preOrder(localRoot.right); 69 } 70 } 71 public void preOrder(){ 72 this.preOrder(this.root); 73 } 74 //后序遍歷方法遞歸實現 75 public void postOrder(Node localRoot){ 76 if (localRoot != null) { 77 postOrder(localRoot.left); 78 postOrder(localRoot.right); 79 System.out.print(localRoot.data + " "); 80 } 81 } 82 public void postOrder(){ 83 this.postOrder(this.root); 84 } 85 86 //層次遍歷(利用一個隊列實現) 87 public static void levelOrder(Node localRoot){ 88 if(localRoot == null) 89 return; 90 List<Node> queue = new LinkedList<Node>(); 91 queue.add(localRoot); 92 while(!queue.isEmpty()){ 93 Node temp = queue.poll(0); 94 System.out.print(temp.data + " "); 95 if(temp.left != null){ 96 queue.add(temp.left); 97 } 98 if(temp.right != null){ 99 queue.add(temp.right); 100 } 101 } 102 System.out.println(); 103 } 104 public void levelOrder(){ 105 this.levelOrder(this.root); 106 } 107 }