자료구조

이진트리 InOrder with Stack

hyunjin-dev-log 2021. 12. 28. 15:04

        public void InOrderWithStack()
        {
            Console.WriteLine("이진트리 중위순회 with Stack");
            Stack stack = new Stack();
            if (this.Root == null)
            {
                Console.WriteLine("노드가 없습니다.");
            }
            else
            {
                Node temp = this.Root;
                Node popNode;

                while (temp != null)
                {
                    stack.Push(temp);
                    if (temp.Left != null)
                    {
                        temp = temp.Left;
                    }
                    else
                    {
                        popNode = stack.Pop();
                        Console.Write("{0} ", popNode.Data);
                        temp = popNode.Right;
                        while (temp == null && stack.Count() > 0)
                        {
                            popNode = stack.Pop();
                            Console.Write("{0} ", popNode.Data);
                            temp = popNode.Right;
                        }
                    }
                }
            }
            Console.WriteLine();
        }