首页 > 代码库 > binarysearchtree
binarysearchtree
1 public class binarytree<Value> { 2 private Node root = null; 3 private class Node{ 4 private Value val; 5 private int key; 6 private Node left,right; 7 private int N; //the number of the all nodes of its child nodes and itself 8 //private int num;//the number 9 public Node(Value val,int key,int N){ 10 this.val = val; this.N = N;this.key = key; 11 } 12 13 } 14 15 public void walk(Node x) { //O(n) time 16 if(x!=null){ 17 walk(x.left); 18 System.out.println(x.key); 19 walk(x.right); 20 } 21 } 22 23 public Value get(Node x,int key){ 24 if(x == null){ 25 return null; 26 } 27 28 if(x.key>key){ 29 return get(x.left,key); 30 } 31 else if(x.key < key){ 32 return get(x.right,key); 33 } 34 else{ 35 return x.val; 36 } 37 } 38 private Node min(Node x){ 39 if(x.left == null) return x; 40 return min(x.left); 41 } 42 43 private Node deletemin(Node x){ 44 if(x.left == null){return x.right;} 45 x.left = deletemin(x.left); 46 x.N = size(x.left) + size(x.right) + 1; 47 return x; 48 } 49 50 51 52 private Node delete(Node x,int key){ 53 if(key < x.key) x.left = delete(x.left,key); 54 else if(key > x.key) x.right = delete(x.right,key); 55 else{ 56 if(x.left == null) return x.right; 57 if(x.right == null) return x.left; 58 Node t = x; 59 x = min(t.right); 60 x.right = deletemin(t.right); 61 x.left = t.left; 62 } 63 x.N = size(x.left) +size(x.right)+1; 64 return x; 65 66 } 67 68 69 70 71 private Node put(Node x,Value val,int key){ 72 if(x == null) return new Node(val,key,1); 73 if(key < x.key) x.left = put(x.left,val,key); 74 else if(key > x.key) x.right = put(x.right,val,key); 75 else x.key = key; 76 x.N = size(x.left) + size(x.right) + 1; 77 return x; 78 } 79 private int size(Node x){ 80 if(x == null){return 0;} 81 else return x.N; 82 } 83 84 85 86 private Node select(Node x,int k){ 87 if(x == null) return null; 88 int t = size(x.left); 89 if (t>k) return select(x.left,k); 90 else if(t<k) return select (x.right,k-t-1); 91 else return x; 92 } 93 94 95 96 }
binarysearchtree
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。