ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 04/01 BinaryTree Preorder 순회 (Iterative) 복습
    자료구조/수업내용 2021. 4. 1. 09:57
    728x90

    순서

    1. 이진트리, 노드 클래스 생성

     

    2. 스택생성

    루트를 스택에 넣음

     

    3. 스택요소가 없을 때 까지 반복

    스택에서 요소를 꺼내 출력

    오른쪽이 null아니면 스택에 넣음
    왼쪽이 null아니면 스택에 넣음

     

     

    Program.cs

    using System;
    
    namespace Study09
    {
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Main");
                new App();
            }
        }
    }
    

     

    App.cs

    using System;
    
    namespace Study09
    {
    
        public class App
        {
    
            //생성자 
            public App()
            {
                Console.WriteLine("App");
    
                BinaryTree tree = new BinaryTree("A");
                var A = tree.root;
                A.left = new BinaryNode("B");
                A.right = new BinaryNode("C");
                A.left.left = new BinaryNode("D");
                A.left.right = new BinaryNode("E");
                A.right.left = new BinaryNode("F");
    
                tree.Print();
            }
    
        }
    }
    

     

    BinaryNode.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Study09
    {
        public class BinaryNode
        {
            public string value;
            public BinaryNode left;
            public BinaryNode right;
            public BinaryNode(string value)
            {
                this.value = value;
            }
        }
    }
    

     

    BinaryTree.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace Study09
    {
        public class BinaryTree
        {
            public BinaryNode root;
            public BinaryTree(string value)
            {
                root = new BinaryNode(value);
            }
    
            public void Print()
            {
                Stack<BinaryNode> stack = new Stack<BinaryNode>();
    
                stack.Push(root);
    
                while(stack.Count > 0)
                {
                    var temp = stack.Pop();
                    Console.Write(temp.value);
    
                    if(temp.right != null)
                    {
                        stack.Push(temp.right);
                    }
    
                    if(temp.left != null)
                    {
                        stack.Push(temp.left);
                    }
                }
            }
        }    
    }
    
    728x90
Designed by Tistory.