天天看点

【愚公系列】2021年11月 C#版 数据结构与算法解析(树)

基本树的实现

public class Tree<T>
    {
        public Tree()
        {
            Deep = 1;
        }

        public int Deep { get; set; } 
        public string Name { get; set; } 
        public T Value { get; set; }
         
        public Tree<T> Perent { get; set; }
         
        private List<Tree<T>> Child = new List<Tree<T>>();
         
        public void AddChild(Tree<T> tree)
        {
            if (GetByName(tree.Name) != null)
            {
                return;
            }
            tree.Perent = this;
            tree.Deep = Deep + 1;
            Child.Add(tree);
        } 
        public void RemoveChild()
        {
            Child.Clear();
        }
         
        public Tree<T> GetByName(string name)
        {
            Tree<T> root = GetRootTree(this);
            List<Tree<T>> list = GatAll(root);
            var result = list.Where(c => c.Name == name).ToList();
            if (result.Count <= 0)
            {
                return null;
            }
            else
            {
                return result[0];
            }
        } 
        public List<Tree<T>> GatAll(Tree<T> tree)
        {
            List<Tree<T>> list = new List<Tree<T>>();
            list.Add(tree);
            if (tree.Child == null)
            {
                return null;
            }
            list.AddRange(tree.Child);
            foreach (var tree1 in tree.Child)
            {
                list.AddRange(GatAll(tree1));
            }
            return list.Distinct().ToList();
        }
         
        public Tree<T> GetRootTree(Tree<T> tree)
        {
            if (tree.Perent == null)
            {
                return tree;
            }
            return GetRootTree(tree.Perent);
        }
         
        public int GetDeep(Tree<T> tree)
        {
            List<Tree<T>> list = GetDeepTree(tree);
            return list.Max(c => c.Deep);
        }
         
        public List<Tree<T>> GetDeepTree(Tree<T> tree)
        {
            List<Tree<T>> list = new List<Tree<T>>();
            if (tree.Child.Count <= 0)
            {
                list.Add(tree);
            }
            else
            {
                foreach (var tree1 in tree.Child)
                {
                    if (tree1.Child.Count <= 0)
                    {
                        list.Add(tree1);
                    }
                    else
                    {
                        foreach (var tree2 in tree1.Child)
                        {
                            list.AddRange(GetDeepTree(tree2));
                        }
                    }
                }
            }
            return list;
        } 
    }      

继续阅读