首页 > 其他 > 详细

使用Integer类实现二叉树排序

时间:2014-08-14 16:15:18      阅读:264      评论:0      收藏:0      [点我收藏+]

class BinaryTree {
    class Node {
        private Comparable data;
        private Node left;
        private Node right;

        public void addNode(Node newNode) {
            if (newNode.data.compareTo(this.data) < 0) {
                if (this.left == null) {
                    this.left = newNode;
                } else {
                    this.left.addNode(newNode);
                }
            }
            if (newNode.data.compareTo(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.print(this.data + "\t");
            if (this.right != null) {
                this.right.printNode();
            }
        }
    };

    private Node root;

    public void add(Comparable data) {
        Node newNode = new Node();
        newNode.data = data;
        if (root == null) {
            root = newNode;
        } else {
            root.addNode(newNode);
        }
    }

    public void print() {
        this.root.printNode();
    }
}

public class ComparebleDemo03 {
    public static void main(String[] args) {
        BinaryTree bt = new BinaryTree();
        bt.add(8);
        bt.add(3);
        bt.add(3);
        bt.add(10);
        bt.add(9);
        bt.add(1);
        bt.add(5);
        bt.add(5);
        System.out.println("After sorted:");
        bt.print();
    }
}

使用Integer类实现二叉树排序,布布扣,bubuko.com

使用Integer类实现二叉树排序

原文:http://www.cnblogs.com/vonk/p/3912526.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!