二叉树的Java实现

public class Node {
    // 数据项
    long data;
    // 左节点
    Node leftChild = null;
    // 右节点
    Node rightChild = null;

    public Node(long data) {
        super();
        this.data = data;
    }

    public static void main(String[] args) {
        /**
         * 特别注意以下两种情况:
         * 
         *   一种 更改的是指向
         * 
         *   一种 更改的是指向对象的属性
         * 
         * 特别是在 组合 的模式中,这堆东西特别容易出错
         */
        //1
        Node n1 = new Node(1);
        Node n2 = n1;
        n2 = new Node(10);
        System.out.println(n1.data);//1
        //2
        Node n3 = n1;
        n3.data = 5;
        System.out.println(n1.data);//5
        //1
        Node current = n1;
        current = current.leftChild;
        current = n2;
        System.out.println(n1.leftChild==n2);//false
        //2   
        current = n1;
        current.leftChild = n2;
        System.out.println(n1.leftChild==n2);//true
        /**
         * 这就是为什么要 引入 Node parent的原因
         */

    }
}

public class Tree {
    // 根节点
    public Node root = null;

    // 插入
    public void insert(long value) {
        //封装
        Node newNode =new Node(value);
        //两个必须的变量
        Node current=root;
        Node parent;
        if(root==null) root=newNode;
        else{
            //子树迭代
            parent=current;
            while(true){
                if(current.data>value){
                    current=current.leftChild;
                    if(current==null){
                        parent.leftChild=newNode;
                        return ;
                    }
                }else{
                    current=current.rightChild;
                    //
                    if(current==null){
                        parent.rightChild=newNode;
                        return;
                    }
                }

            }
        }

    }

    public static void main(String[] args) {
        Tree tree = new Tree();
        tree.insert(10);
        tree.insert(15);
        tree.insert(13);
        tree.insert(3);
        tree.insert(20);
        System.out.println(tree.root.leftChild.data);

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值