コード例 #1
0
        private static NodeWithNext ConnectLevelOrderSiblingsV2(NodeWithNext root)
        {
            var nodes = new Queue <NodeWithNext>();

            nodes.Enqueue(root);
            NodeWithNext previous = null;

            while (nodes.Count > 0)
            {
                var current = nodes.Dequeue();
                if (previous == null)
                {
                    previous = current;
                }
                else
                {
                    previous.Next = current;
                    previous      = current;
                }

                if (current.Left != null)
                {
                    nodes.Enqueue(current.Left);
                }
                if (current.Right != null)
                {
                    nodes.Enqueue(current.Right);
                }
            }

            return(root);
        }
コード例 #2
0
        private static NodeWithNext ConnectLevelOrderSiblings(NodeWithNext root)
        {
            var nodes = new Queue <NodeWithNext>();
            var temp  = new Queue <NodeWithNext>();

            nodes.Enqueue(root);
            while (nodes.Count > 0 || temp.Count > 0)
            {
                if (nodes.Count == 0)
                {
                    nodes = temp;
                    temp  = new Queue <NodeWithNext>();
                }
                else
                {
                    var current = nodes.Dequeue();
                    if (nodes.Count > 0)
                    {
                        current.Next = nodes.Peek();
                    }

                    if (current.Left != null)
                    {
                        temp.Enqueue(current.Left);
                    }
                    if (current.Right != null)
                    {
                        temp.Enqueue(current.Right);
                    }
                }
            }

            return(root);
        }
コード例 #3
0
        public static void Print(NodeWithNext root)
        {
            var queue = new Queue <NodeWithNext>();

            queue.Enqueue(root);
            while (queue.Count > 0)
            {
                var current = queue.Dequeue();
                var next    = current.Next != null?current.Next.Value.ToString() : "";

                Console.WriteLine($"[{current.Value} -> {next}]");
                if (current.Left != null)
                {
                    queue.Enqueue(current.Left);
                }
                if (current.Right != null)
                {
                    queue.Enqueue(current.Right);
                }
            }
        }