首页 > 编程语言 > 详细

二叉排序树

时间:2019-06-12 14:26:27      阅读:111      评论:0      收藏:0      [点我收藏+]

一、基本数据结构

public class Node<T>{
    private T value;
    private int height;
    private Node<T> left;
    private Node<T> right;
    public Node(T value) {
        this.value = value;
        this.height = 1;
        this.left = null;
        this.right = null;
    }
    public T getValue() {
        return value;
    }
    public void setValue(T value) {
        this.value = value;
    }
    public int getHeight() {
        return height;
    }
    public void setHeight(int height) {
        this.height = height;
    }
    public Node<T> getLeft() {
        return left;
    }
    public void setLeft(Node<T> left) {
        this.left = left;
    }
    public Node<T> getRight() {
        return right;
    }
    public void setRight(Node<T> right) {
        this.right = right;
    }
    @Override
    public String toString() {
        // TODO Auto-generated method stub
        return this.value.toString();
    }
}

二、普通二叉排序树

1、二叉排序树的insert(非递归)[个人觉得非递归算法更优,因为它不需要回溯]

    public static <T> Node<T> insert(Node<T> root, T value){
        Node<T> node = new Node<T>(value);
        if(root == null) {
            return node;
        }
        int temp = 0;
        Node<T> prev = root;
        while(prev!=null) {
            temp = ((Comparable)prev.getValue()).compareTo(value);
            if(temp == 0) {
                return root;
            }else if(temp == 1) {
                if(prev.getLeft()==null) {
                    prev.setLeft(node);
                }
                prev = prev.getLeft();
            }else {
                if(prev.getRight()==null) {
                    prev.setRight(node);
                }
                prev = prev.getRight();
            }
        }
        return root;
    }

2、二叉排序树的insert(递归)

二叉排序树

原文:https://www.cnblogs.com/erdanyang/p/11009198.html

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