(精华)2020年8月28日 数据结构与算法解析(二叉树排序)

举报
愚公搬代码 发表于 2021/10/19 00:26:27 2021/10/19
【摘要】 1、二叉树排序 二叉树排序是构建在二叉排序树(Binary Sort Tree)上的算法,二叉排序树或者是一棵空树,或者是具有下列性质的二叉树。二叉树排序需要先生成一个二叉排序树,再使用中序遍历输出所有...

1、二叉树排序

二叉树排序是构建在二叉排序树(Binary Sort Tree)上的算法,二叉排序树或者是一棵空树,或者是具有下列性质的二叉树。二叉树排序需要先生成一个二叉排序树,再使用中序遍历输出所有数据。

1.1 算法描述

二叉树排序是构建在二叉排序树(Binary Sort Tree)上的算法,二叉排序树或者是一棵空树,或者是具有下列性质的二叉树:

  • 若左子树不空,则左子树上所有结点的值均小于或等于它的根结点的值;
  • 若右子树不空,则右子树上所有结点的值均大于或等于它的根结点的值;
  • 左、右子树也分别为二叉排序树。

二叉树排序需要先生成一个二叉排序树,再使用中序遍历输出所有数据。

1.2 图片演示

在这里插入图片描述

1.3 代码实现

public class BinarySortTreeNode {

    public int Key { get; set; }

    public BinarySortTreeNode Left { get; set; }

    public BinarySortTreeNode Right { get; set; }

    public BinarySortTreeNode(int key) {
        Key = key;
    }

    public void Insert(int key) {
        var tree = new BinarySortTreeNode(key);
        if (tree.Key <= Key) {
            if (Left == null) {
                Left = tree;
            }
            else {
                Left.Insert(key);
            }
        }
        else {
            if (Right == null) {
                Right = tree;
            }
            else {
                Right.Insert(key);
            }
        }
    }

    /// <summary>
    /// 中序遍历
    /// </summary>
    public void InorderTraversal() {
        Left?.InorderTraversal();
        Console.Write($"{Key} ");
        Right?.InorderTraversal();
    }

}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
public class Program {

    public static void Main(string[] args) {
        int[] array = { 43, 69, 11, 72, 28, 21, 56, 80, 48, 94, 32, 8 };

        BinaryTreeSort(array);

        Console.ReadKey();
    }

    public static void BinaryTreeSort(int[] array) {
        var binarySortTreeNode = new BinarySortTreeNode(array[0]);
        for (int i = 1; i < array.Length; i++) {
            binarySortTreeNode.Insert(array[i]);
        }
        binarySortTreeNode.InorderTraversal();
    }

}

  
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

二叉树排序算法的时间复杂度为:O(n*logn) 。

文章来源: codeboy.blog.csdn.net,作者:愚公搬代码,版权归原作者所有,如需转载,请联系作者。

原文链接:codeboy.blog.csdn.net/article/details/108279119

【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。