zoukankan      html  css  js  c++  java
  • 二叉排序树 bst 创建和遍历

    package jiegou.bst;
    
    import sun.font.GlyphLayout;
    import sun.nio.cs.ext.TIS_620;
    
    // 二叉排序树
    public class BinarySortTreeDemo {
        public static void main(String[] args) {
            int[] arr = {7,3,10,12,5,1,9};
    
            BinarySortTree binarySortTree = new BinarySortTree();
            // 循环添加节点到树
            for (int i = 0; i < arr.length; i++) {
                binarySortTree.addNode(new Node(arr[i]));
            }
            
            binarySortTree.infixOrder();
        }
    }
    
    class BinarySortTree
    {
        public Node root;
    
        public void addNode(Node node){
            if(root == null) {
                root = node;
            } else {
                root.addNode(node);
            }
        }
    
        public void infixOrder()
        {
            if(root == null) {
                System.out.println("树为空");
                return ;
            }
    
            root.infixOrder();
    
        }
    }
    
    class Node{
        @Override
        public String toString() {
            return "Node{" +
                    "value=" + value +
                    '}';
        }
    
        public int value;
        public Node left;
        public Node right;
    
        public Node(int value){
            this.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);
                }
            }
    
            if(node.value > this.value) {
                if(this.right == null){
                    this.right = node;
                } else {
                    this.right.addNode(node);
                }
            }
    
        }
    
    
        public void infixOrder()
        {
            if(this.left != null) {
                this.left.infixOrder();
            }
    
            System.out.println(this);
    
            if(this.right != null) {
                this.right.infixOrder();
            }
        }
    }
    

    中序遍历结果

    Node{value=1}
    Node{value=3}
    Node{value=5}
    Node{value=7}
    Node{value=9}
    Node{value=10}
    Node{value=12}
    
  • 相关阅读:
    centos shell运行报语法错误: 未预期的文件结尾
    腾讯云防暴力破解防异地登陆
    centos常用命令
    centos7安装nginx
    JavaScript数组倒序函数reverse()
    Ecshop首页购物车数量调取问题
    (原)IPhone开发时把ToolBar中的元素居中的技巧
    iphone开发常用代码笔记
    Windows环境下使用Apache+mod
    [转]C++中sizeof(struct)怎么计算?
  • 原文地址:https://www.cnblogs.com/brady-wang/p/15144098.html
Copyright © 2011-2022 走看看