二叉树查找插入

public class BinaryTree<K extends Comparable, V extends Comparable> {

private Node root;


public Node getRoot() {
    return root;
}

public void setRoot(Node root) {
    this.root = root;
}

public void insert(K key, V value) {
    //如果根节点为空
    if (this.root == null) {
        this.root = new Node(key, value, null, null, null);

        return;
    }

    Node temp = this.root;
    int i = 0;

    Node parent = null;

    while (temp != null) {
        parent = temp;
        i = key.compareTo((K) this.root.key);
        if (i > 0) {
            temp = temp.right;

        } else if (i == 0) {
            temp.value = value;

        } else {
            temp = temp.left;

        }
    }

    if (i > 0) {
        parent.right = new Node(key, value, null, null, parent);
    } else {
        parent.left = new Node(key, value, null, null, parent);
    }

}

public Node select(K key) {
    if (this.root == null) {
        return null;
    }
    Node temp = this.root;

    while (temp != null) {
        int i = key.compareTo(this.root.key);
        if (i == 0) {
            return temp;
        } else if (i > 0) {
            temp = temp.right;

        } else {
            temp = temp.left;
        }

    }

    return null;
}


class Node<K, V> {
    private K key;
    private V value;

    private Node right;

    private Node left;

    private Node parent;

    public Node() {
    }

    public Node(K key, V value, Node right, Node left, Node parent) {
        this.key = key;
        this.value = value;
        this.right = right;
        this.left = left;
        this.parent = parent;
    }

    public K getKey() {
        return key;
    }

    public void setKey(K key) {
        this.key = key;
    }

    public V getValue() {
        return value;
    }

    public void setValue(V value) {
        this.value = value;
    }

    public Node getRight() {
        return right;
    }

    public void setRight(Node right) {
        this.right = right;
    }

    public Node getLeft() {
        return left;
    }

    public void setLeft(Node left) {
        this.left = left;
    }

    public Node getParent() {
        return parent;
    }

    public void setParent(Node parent) {
        this.parent = parent;
    }
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值