完美二叉树

不废话,直接上代码

 

class BinaryTree { // 定义二叉树的操作类
	class Node {
		private Comparable data; // 保存数据
		private Node left;// 表示左子树
		private Node right;// 表示右子树
		public Node(Comparable data) {
			this.data = data;
		}
		public void addNode(Node newNode) {
			if (((Integer)(newNode.data)).compareTo((Integer)(this.data)) < 0) {
				if (this.left == null) { // 当前的左子树是否等于空
					this.left = newNode;
				} else {
					this.left.addNode(newNode);// 继续向下继续判断
				}
			}
			if (((Integer)(newNode.data)).compareTo((Integer)(this.data)) >= 0) {
				if (this.right == null) { // 当前的右子树是否等于空
					this.right = newNode;
				} else {
					this.right.addNode(newNode);
				}
			}
		}
		public void printNode() {
			if (this.left != null) {
				this.left.printNode();
			}
			System.out.println(this.data);
			if (this.right != null) {
				this.right.printNode();
			}
		}
	}
	private Node root; // 定义根节点
	public void add(Comparable data) { // 表示增加节点
		Node newNode = new Node(data);
		if (this.root == null) { // 此时没有根节点,第一个元素作为根节点
			this.root = newNode;
		} else { // 判断节点是放在左子树还是右子树
			this.root.addNode(newNode);
		}
	}
	public void print() { // 打印节点
		this.root.printNode();
	}
}


public class BinaryTreeDemo {
	public static void main(String[] args) {
		BinaryTree bt = new BinaryTree();
		bt.add(5);
		bt.add(3);
		bt.add(1);
		bt.add(90);
		bt.add(90);
		bt.add(100);
		bt.add(60);
		bt.print();
	}
}


 

 

posted on 2013-09-16 19:56  新一  阅读(238)  评论(0编辑  收藏  举报

导航