java数据结构(二叉树)
Node节点:
1 public class Node { 2 public long data; 3 public String sData; 4 public Node leftChild; 5 public Node rightChild; 6 public Node(long data,String sData) { 7 this.data = data; 8 this.sData = sData; 9 } 10 }
Tree:
1 public class Tree { 2 public Node root; 3 4 public void insert(long value,String sValue){ 5 Node newNode = new Node(value,sValue); 6 Node current = root; 7 Node parent; 8 if(root == null){ 9 root = newNode; 10 return; 11 }else{ 12 while(true){ 13 parent = current; 14 if(current.data > value){ 15 current = current.leftChild; 16 if(current == null){ 17 parent.leftChild = newNode; 18 return ; 19 } 20 }else{ 21 current = current.rightChild; 22 if(current == null){ 23 parent.rightChild = newNode; 24 return; 25 } 26 } 27 } 28 } 29 } 30 31 public Node find(long value){ 32 Node current = root; 33 while(current.data != value){ 34 if(current.data > value){ 35 current = current.leftChild; 36 }else{ 37 current = current.rightChild; 38 } 39 if(current == null){ 40 return null; 41 } 42 } 43 return current; 44 } 45 }