C#/수업 내용

[C#] 이진 트리 level order traversal

JSH1 2021. 9. 27. 11:42

    class App
    {
        public App()
        {
            BinaryTree bt = new BinaryTree();
            Node root = bt.AddChild(bt.Root, 1);
            bt.AddChild(root, 2);
            bt.AddChild(root, 3);
            bt.AddChild(root, 4);
            bt.AddChild(root, 5);
            bt.AddChild(root, 6);
            bt.AddChild(root, 7);

            bt.LevelOrder(root);
        }
    }
    class BinaryTree
    {
        public class Node
        {
            public int Data { get; private set; }
            public Node Left;
            public Node Right;

            public Node(int data)
            {
                Data = data;
            }
        }

        public Node Root { get; private set; }

        public void LevelOrder(Node root)
        {
            if (root == null) return;

            Queue<Node> nodes = new Queue<Node>();
            nodes.Enqueue(root);

            while (true)
            {
                root = nodes.Dequeue();
                Console.WriteLine(root.Data);

                if (root.Left != null)
                {
                    nodes.Enqueue(root.Left);

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

                if (nodes.Count == 0) return;
            }
        }

        public Node AddChild(Node root, int data)
        {
            if (root == null)
            {
                Console.WriteLine("root node: {0}", data);
                return new Node(data);
            }

            else
            {
                return AddChildRecursive(root, data);
            }
        }

        public Node AddChildRecursive(Node root, int data)
        {
            if (root.Left == null)
            {
                Console.WriteLine("Parent Node: {0}, AddChild Left Node: {1}", root.Data, data);
                return root.Left = new Node(data);
            }

            else if (root.Left.Right == null)
            {
                Console.WriteLine("{0} Sibling Node: {1}", root.Left.Data, data);
                return root.Left.Right = new Node(data);
            }

            else
            {
                if (root.Left.Left == null || root.Left.Left.Right == null)
                {
                    return AddChildRecursive(root.Left, data);
                }

                else if (root.Left.Right.Left == null || root.Left.Right.Left.Right == null)
                {
                    return AddChildRecursive(root.Left.Right, data);
                }

                else
                {
                    throw new InvalidOperationException();
                }
            }
        }
    }

'C# > 수업 내용' 카테고리의 다른 글

[C#] 배열 Binary Tree  (0) 2021.09.29
[C#] 이진 트리 Left Skewed Tree, Recursive Print  (0) 2021.09.27
[C#] 일반 트리 level order traversal  (0) 2021.09.26
[C#] Tree  (0) 2021.09.24
[C#] Queue 복습  (0) 2021.09.24