您现在的位置是:首页 > 后台技术 > 数据结构与算法数据结构与算法

二叉排序树的创建(图文)

第十三双眼睛2023-10-21【数据结构与算法】人已围观

简介二叉排序树的创建

二叉排序树的创建
package com.xingchen.day013;
public class BinSortTreeDemo {
    public static void main(String[] args) {
        int[] arr = {7,3,10,12,5,1,9};
        BinSortTree binSortTree = new BinSortTree();
        for (int i = 0; i<arr.length; i++) {
            binSortTree.add(new Node(arr[i]));
        }
        binSortTree.infixOrder();
    }
}
class BinSortTree{
    public Node root;
    public void add(Node node) {
        if (root == null) {
            root = node;
        } else {
            root.add(node);
        }
    }
    public void infixOrder() {
        if (root != null) {
            root.infixOrder();
        } else {
            System.out.println("二叉排序树为空");
        }
    }
}
class Node {
    public int value;
    public Node left;
    public Node right;
    public Node(int value) {
        this.value = value;
    }
    public void add(Node node) {
        if (node == null) {
            return;
        }
        if (node.value < this.value) {
            if (this.left == null) {
                this.left = node;
            } else {
                this.left.add(node);
            }
        } else {
            if (this.right == null) {
                this.right = node;
            } else {
                this.right.add(node);
            }
        }
    }
    public void infixOrder() {
        if (this.left != null) {
            this.left.infixOrder();
        }
        System.out.println(this);
        if (this.right != null) {
            this.right.infixOrder();
        }
    }
    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }
}

Tags:

很赞哦! ()

文章评论

    共有条评论来说两句吧...

    用户名:

    验证码:

本站推荐

站点信息

  • 网站名称:JavaStudy
  • 建站时间:2019-1-14
  • 网站程序:帝国CMS7.5
  • 文章统计242篇文章
  • 标签管理标签云
  • 统计数据百度统计
  • 微信公众号:扫描二维码,关注我们