标签:style pat ring his 实现 turn main 遍历 null
一、用Integer为Comparable接口实例化
为了简化代码,直接使用Integer类,因为Integer类;已经实现了Comparable接口。
1 package comparabledemo; 2 3 public class ComparableDemo02 { 4 5 public static void main(String[] args) { 6 Comparable com = null; 7 com =30; //实例化Comparable接口 8 System.out.println(com); //实际上调用的是toString()方法 9 } 10 11 }
二、二叉树的元素添加、中序遍历、深度
1 package comparabledemo; 2 3 class BinaryTree{ 4 class Node{ 5 private Comparable data; 6 private Node left; 7 private Node right; 8 public void addNode(Node newNode){ 9 if(newNode.data.compareTo(this.data)<0){ 10 if(this.left == null){ 11 this.left = newNode; 12 }else{ 13 this.left.addNode(newNode); 14 } 15 } 16 if(newNode.data.compareTo(this.data)>=0){ 17 if(this.right ==null){ 18 this.right = newNode; 19 }else{ 20 this.right.addNode(newNode); 21 } 22 } 23 } 24 public void printNode(){ 25 if(this.left != null){ 26 this.left.printNode(); 27 } 28 System.out.println(this.data); 29 if(this.right != null){ 30 this.right.printNode(); 31 } 32 } 33 public int treeDepth(Node node){ 34 int deptleft,deptright; 35 if(node == null){ 36 return 0; 37 }else{ 38 deptleft = treeDepth(node.left); 39 deptright = treeDepth(node.right); 40 if(deptleft>deptright){ 41 return deptleft + 1; 42 }else{ 43 return deptright + 1; 44 } 45 } 46 } 47 } 48 private Node root; 49 public void add(Comparable data){ 50 Node newNode = new Node(); 51 newNode.data = data; 52 if(root == null){ 53 root = newNode; 54 }else{ 55 root.addNode(newNode); 56 } 57 } 58 public void print(){ 59 this.root.printNode(); 60 } 61 public void Depth(){ 62 int dept; 63 if(this.root == null){ 64 dept = 0; 65 }else{ 66 dept = this.root.treeDepth(this.root); 67 } 68 System.out.println(dept); 69 } 70 } 71 72 public class CompatableDemo03 { 73 74 public static void main(String[] args) { 75 BinaryTree bt = new BinaryTree(); 76 77 bt.add(8); 78 bt.add(3); 79 //bt.add(3); 80 bt.add(10); 81 bt.add(9); 82 bt.add(1); 83 bt.add(5); 84 //bt.add(5); 85 //bt.print(); 86 bt.Depth(); 87 } 88 }
标签:style pat ring his 实现 turn main 遍历 null
原文地址:http://www.cnblogs.com/XuGuobao/p/7365368.html