二叉排序树

简介: 特点:  若左子树不空,则左子树上所有结点的值均小于它的根结点的值;  若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值;  左、右子树也分别为二叉排序树,这点很重要,

特点:


  若左子树不空,则左子树上所有结点的值均小于它的根结点的值;


  若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值;


  左、右子树也分别为二叉排序树,这点很重要,



代码:


package Tree;
public class SortTree {
    public static void main(String[] args) {
      //添加
      int array[] = {1,4,6,2,8,3,12,90,45,32,89};
      BinarySortTree binarySortTree = new BinarySortTree();
      //循环添加结点
      for (int i = 0 ; i < array.length ; i++){
          binarySortTree.addNode(new Node(array[i]));
      }
      //中序遍历
      binarySortTree.preOrder();
    }
}
class BinarySortTree{
    //根结点
    private Node root;
    public void setRoot(Node root) {
        this.root = root;
    }
    //添加结点
    public void addNode(Node node){
        if (this.root == null){
            root = node;
        }else {
            this.root.addNode(node);
        }
    }
    //先序遍历
    public void preOrder(){
        if (this.root != null){
            this.root.preOrder();
        }else {
            System.out.println("空树");
        }
    }
}
class Node{
    int value;//结点的值
    Node left;//左子树
    Node right;//右子树
    public Node(int value) {
        this.value = value;
    }
    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }
    //添加结点
    public void addNode(Node node){
        if (node == null){
            return;
        }
        if (node.value < this.value){
            if (this.left == null){
                this.left = node;
            }else {
                this.left.addNode(node);
            }
        }
        else {
            if (node.value > this.value){
                if (this.right == null){
                    this.right = node;
                }else {
                    this.right.addNode(node);
                }
            }
        }
    }
    //前序遍历
    public void preOrder() {
        //输出root结点
        System.out.println(this);
        if (this.left != null) {
            this.left.preOrder();//递归左子结点
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }
}



目录
相关文章
|
5月前
|
存储 C++
二叉树搜索树的应用
二叉树搜索树的应用
35 1
|
8天前
二叉搜索树
二叉搜索树
14 2
|
9月前
二叉排序树(BST)
二叉排序树(BST)
51 0
|
8天前
|
存储 安全 C++
C++【二叉搜索树】
C++【二叉搜索树】
41 0
|
9月前
|
编译器 C语言 C++
【C++】二叉搜索树
【C++】二叉搜索树
41 0
|
11月前
|
算法
二叉搜索树、平衡二叉树
一、二叉搜索树 这里我们不用太多书面化的语言来定义,笔者认为在讨论数据结构、算法相关的内容时用太多书面化、学术化的语言是一种让人很烦的事情。咬文嚼字,不便于读者理解。 简单来说二叉树搜索树,其实就是用来做二分查找的一种二叉树。 特点是:根节点的左子树值均小于根节点的值,根节点的右子树值均大于根节点的值。 比如123 4 567建树的结果就是
38 0
|
11月前
【二叉树OJ题(二)】前序遍历&&中序遍历&&后序遍历&&另一颗树的子树&&二叉树遍历&&平衡二叉树(上)
【二叉树OJ题(二)】前序遍历&&中序遍历&&后序遍历&&另一颗树的子树&&二叉树遍历&&平衡二叉树(上)
|
11月前
|
存储 搜索推荐
【二叉树OJ题(二)】前序遍历&&中序遍历&&后序遍历&&另一颗树的子树&&二叉树遍历&&平衡二叉树(下)
【二叉树OJ题(二)】前序遍历&&中序遍历&&后序遍历&&另一颗树的子树&&二叉树遍历&&平衡二叉树(下)
|
12月前
|
C++
【C++】二叉搜索树(上)
【C++】二叉搜索树
48 0

热门文章

最新文章