加入收藏 | 设为首页 | 会员中心 | 我要投稿 焦作站长网 (https://www.0391zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 服务器 > 安全 > 正文

算法系列15天速成 第十一天 树操作(上)

发布时间:2020-03-14 19:10:46 所属栏目:安全 来源:站长网
导读:我们可以对”线性结构“改造一下,变为”一个节点最多有一个前驱“和”多个后继“。哈哈,这就是我们今天说的”树“

#region 插入节点操作
        /// <summary>
/// 插入节点操作
/// </summary>
/// <param></param>
        static ChainTree<string> AddNode(ChainTree<string> tree)
        {
            ChainTreeManager mananger = new ChainTreeManager();

while (true)
            {
                ChainTree<string> node = new ChainTree<string>();

Console.WriteLine("请输入要插入节点的数据:n");

node.data = Console.ReadLine();

Console.WriteLine("请输入要查找的父节点数据:n");

var parentData = Console.ReadLine();

if (tree == null)
                {
                    Console.WriteLine("未找到您输入的父节点,请重新输入。");
                    continue;
                }

Console.WriteLine("请确定要插入到父节点的:1 左侧,2 右侧");

Direction direction = (Direction)Enum.Parse(typeof(Direction), Console.ReadLine());

tree = mananger.BinTreeAddNode(tree, node, parentData, direction);

Console.WriteLine("插入成功,是否继续?  1 继续, 2 退出");

if (int.Parse(Console.ReadLine()) == 1)
                    continue;
                else
                    break;
            }

return tree;
        }
        #endregion
    }

#region 插入左节点或者右节点
    /// <summary>
/// 插入左节点或者右节点
/// </summary>
    public enum Direction { Left = 1, Right = 2 }
    #endregion

#region 二叉链表存储结构
    /// <summary>
/// 二叉链表存储结构
/// </summary>
/// <typeparam></typeparam>
    public class ChainTree<T>
    {
        public T data;

public ChainTree<T> left;

public ChainTree<T> right;
    }
    #endregion

/// <summary>
/// 二叉树的操作帮助类
/// </summary>
    public class ChainTreeManager
    {
        #region 按层遍历的Length空间存储
        /// <summary>
/// 按层遍历的Length空间存储
/// </summary>
        public int Length { get; set; }
        #endregion

#region 将指定节点插入到二叉树中
        /// <summary>
/// 将指定节点插入到二叉树中
/// </summary>
/// <typeparam></typeparam>
/// <param></param>
/// <param></param>
/// <param>插入做左是右</param>
/// <returns></returns>
        public ChainTree<T> BinTreeAddNode<T>(ChainTree<T> tree, ChainTree<T> node, T data, Direction direction)
        {
            if (tree == null)
                return null;

if (tree.data.Equals(data))
            {
                switch (direction)
                {
                    case Direction.Left:
                        if (tree.left != null)
                            throw new Exception("树的左节点不为空,不能插入");
                        else
                            tree.left = node;

(编辑:焦作站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读