code:
/**
*
*/
package com.algorithms;
/**
* @author oracle
*
*/
class BinaryNode {
private int id;
private BinaryNode left;
private BinaryNode right;
public BinaryNode() {
}
// composite模式实现binay tree
//
// public void addNode(BinaryNode node) {
// if (node.getId() > id) {
// if (left == null)
// this.left = node;
// else
// this.left.addNode(node);
// } else {
// if (right == null)
// this.right = node;
// else
// this.right.addNode(node);
// }
//
// }
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public BinaryNode getLeft() {
return left;
}
public void setLeft(BinaryNode left) {
this.left = left;
}
public BinaryNode getRight() {
return right;
}
public void setRight(BinaryNode right) {
this.right = right;
}
}
public class BinaryTree {
// 添加一个节点到二叉树
// 下面的代码显示一个对象的名字相当于指向一个对象的handle
public static void addNode(BinaryNode root, BinaryNode node) {
BinaryNode newnode = root;
while (newnode != null) {
if (newnode.getId() < node.getId()) {
if (newnode.getLeft() == null) {
newnode.setLeft(node);
newnode = null;
} else {
newnode = newnode.getLeft();
}
} else {
if (newnode.getRight() == null) {
newnode.setRight(node);
newnode = null;
} else
newnode = newnode.getRight();
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BinaryNode root = new BinaryNode();
root.setId(50);
BinaryNode one = new BinaryNode();
one.setId(80);
BinaryTree.addNode(root, one);
BinaryNode two = new BinaryNode();
two.setId(40);
BinaryTree.addNode(root, two);
BinaryNode three = new BinaryNode();
three.setId(90);
BinaryTree.addNode(root, three);
}
}
posted on 2007-04-09 03:10
Coundy 阅读(448)
评论(0) 编辑 收藏 所属分类:
Java