首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > 移动开发 >

完善二叉树

2013-09-16 
完美二叉树不废话,直接上代码class BinaryTree { // 定义二叉树的操作类class Node {private Comparable d

完美二叉树

不废话,直接上代码

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();}}


热点排行