一个二叉树的实现demo
image.pngpublic class BalanceTree {
public static String TAG = "BalanceTree";
public static class Node{
public int i;
public Node left;
public Node right;
public Node(int i) {
this.i = i;
}
public void addNode(Node node){
if (node.i <= i){
if (left == null){
left = node;
}else{
left.addNode(node);
}
}else{
if (right == null){
right = node;
}else {
right.addNode(node);
}
}
}
public void print(){
if (left != null){
Log.i(TAG,left.i+"");
left.print();
}
if (right != null){
Log.i(TAG,right.i+"");
right.print();
}
}
}
private Node rootNode;
public void add(Node node){
if (rootNode == null){
rootNode = node;
}else{
rootNode.addNode(node);
}
}
//中 左 右
public void print(){
if (rootNode != null){
Log.i(TAG,rootNode.i+"");
rootNode.print();
}
}
}
BalanceTree balanceTree = new BalanceTree();
balanceTree.add(new BalanceTree.Node(8));
balanceTree.add(new BalanceTree.Node(3));
balanceTree.add(new BalanceTree.Node(10));
balanceTree.add(new BalanceTree.Node(1));
balanceTree.add(new BalanceTree.Node(6));
balanceTree.add(new BalanceTree.Node(14));
balanceTree.add(new BalanceTree.Node(4));
balanceTree.add(new BalanceTree.Node(7));
balanceTree.add(new BalanceTree.Node(13));
balanceTree.print();
输出
10-18 20:52:26.218 8793-8793/demo.huangli.mydemosnew I/BalanceTree: 8
10-18 20:52:26.218 8793-8793/demo.huangli.mydemosnew I/BalanceTree: 3
10-18 20:52:26.218 8793-8793/demo.huangli.mydemosnew I/BalanceTree: 1
10-18 20:52:26.218 8793-8793/demo.huangli.mydemosnew I/BalanceTree: 6
10-18 20:52:26.218 8793-8793/demo.huangli.mydemosnew I/BalanceTree: 4
10-18 20:52:26.218 8793-8793/demo.huangli.mydemosnew I/BalanceTree: 7
10-18 20:52:26.218 8793-8793/demo.huangli.mydemosnew I/BalanceTree: 10
10-18 20:52:26.218 8793-8793/demo.huangli.mydemosnew I/BalanceTree: 14
10-18 20:52:26.218 8793-8793/demo.huangli.mydemosnew I/BalanceTree: 13
网友评论