C#/수업 내용

[C#] 이진 트리 in-order(중위 순회)

JSH1 2021. 9. 30. 09:53


중위 순회 in-order Recursive

        public void InOrder(Node root) // 이진 트리 Recursive in-order
        {
            if (root.Left != null) InOrder(root.Left);
            Console.WriteLine(root.Data);
            if (root.Right != null) InOrder(root.Right);
        }


중위 순회 in-order Stack

        public void InOrderStack(Node root) // 이진 트리 Stack in-order
        {
            Stack<Node> nodes = new Stack<Node>();

            while (true)
            {
                while (root != null)
                {
                    nodes.Push(root);
                    root = root.Left;
                }

                if (nodes.Count == 0) return;

                root = nodes.Pop();
                Console.WriteLine(root.Data);

                root = root.Right;
            }
        }