美文网首页
求二叉树上某一深度上的所有节点,并用链表表示这些节点

求二叉树上某一深度上的所有节点,并用链表表示这些节点

作者: 周末的游戏之旅 | 来源:发表于2019-08-03 10:55 被阅读0次

    问题描述

    给定一颗二叉树,创建包含有某一深度上所有节点的链表。
    即输入一颗二叉树和要求的深度,返回一个链表。
    也就是求二叉树上某一深度上的所有节点

    namespace TreeToLinkList
    {
        class Tree
        {
            public string data;
            public Tree left;
            public Tree right;
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                Tree tree = new Tree()
                {
                    data = "a",
                    left = new Tree() { data = "b" },
                    right = new Tree()
                    {
                        data = "c",
                        left = new Tree() { data = "d" },
                        right = new Tree() { data = "e" },
                    }
                };
                LinkedList<string> ls = GetTreeLevel(tree, 3);
    
                LinkedListNode<string> lsNode = ls.First;
                while (lsNode != null)
                {
                    Console.WriteLine(lsNode.Value);
                    lsNode = lsNode.Next;
                }
            }
    
            static LinkedList<string> GetTreeLevel(Tree root,int depth)
            {
                LinkedList<string> list = new LinkedList<string>();
    
                if (root == null || depth < 0)
                {
                    return null;
                }
                GetListNode(root, depth, list);
                return list;
            }
    
            static void GetListNode(Tree node, int depth,LinkedList<string> list)
            {
                if (node == null) return;
                if (depth == 1)
                {
                    list.AddLast(node.data);
                    return;
                }
                GetListNode(node.left, depth - 1, list);
                GetListNode(node.right, depth - 1, list);
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:求二叉树上某一深度上的所有节点,并用链表表示这些节点

          本文链接:https://www.haomeiwen.com/subject/uitjdctx.html