First, the tree itself is a natural organizational structure
After the data using a tree structure, surprisingly efficient.
Second, the binary tree
And the same list, the dynamic data structure
class Node{
And is;
Node left;
Node right;
}
Binary tree (multi-tree)
Binary tree has a unique root
class Node{
And is;
Node left; <- left child
Node right; <- right child
}
Binary tree every node has at most two children nodes
Binary tree each node has at most one parent
Recursive binary tree structure has a natural
Each node of the left subtree is a binary tree
Each node of the right subtree is a binary tree
Binary tree is not necessarily a "full",
Such as: a node is a binary tree 10
NULL binary tree is empty
Third, the binary search tree (Binary Search Tree)
Binary search tree is a binary tree
Each node of the binary search tree values:
The value of all the nodes larger than its left subtree
Values of all the nodes is smaller than the right subtree
Each sub-tree is a binary search tree
There must be an element stored comparability
1 public class BST<E extends Comparable<E>> { 2 3 private class Node { 4 public E e; 5 public Node left, right; 6 7 public Node(E e) { 8 this.e = e; 9 left = null; 10 right = null; 11 } 12 } 13 14 private Node root; 15 private intsize; 16 . 17 public the BST () { 18 is the root = null ; . 19 size = 0 ; 20 is } 21 is 22 is public int size () { 23 is return size; 24 } 25 26 is public Boolean isEmpty () { 27 return size == 0 ; 28 } 29 30 // Add a new element e to the binary search tree 31 is public void the Add (E e) { 32 IF ( null ==the root) { 33 is the root = new new the Node (E); 34 is size ++ ; 35 } the else { 36 the Add (the root, E); // be written 37 [ } 38 is 39 // size ++; 40 } 41 is 42 is 43 is // the node is in root binary search tree insert elements e, a recursive algorithm 44 is Private void the Add (the Node Node, E E) { 45 / * 46 is IF (Node == null || node.e == E) {// == distinction equals the difference between 47 Node the Node new new = (E);
size ++; 48 return; 49 }else if(node.e > e){ 50 add(node.left,e); 51 }else{ 52 add(node.right,e); 53 } 54 */ 55 if(e.equals(node.e)){ 56 return; 57 }else if(e.compareTo(node.e) < 0 && null == node.left){ 58 node.left = new Node(e); 59 size++; 60 return; 61 }else if(e.compareTo(node.e) > 0 && null == node.right){ 62 node.right = new Node(e); 63 size++; 64 return; 65 } 66 67 if(e.compareTo(node.e) < 0 ){ 68 add(node.left, e); 69 }else{ 70 add(node.right, e); 71 } 72 73 } 74 }