예제 #1
0
        public void postOrderTraversal(BST root)
        {
            // Left, Right , Root Node
            // if(root != null)
            // {
            //     postOrderTraversal(root.left);
            //     postOrderTraversal(root.right);
            //     Write($" {root.data} ");
            // }

            if (root == null)
            {
                return;
            }

            Stack <BST> stack = new Stack <BST>();

            stack.Push(root);

            while (stack.Count != 0)
            {
                BST currentNode = stack.Peek();

                stack.Pop();

                if (currentNode.left != null)
                {
                    stack.Push(currentNode.left);
                }

                if (currentNode.right != null)
                {
                    stack.Push(currentNode.right);
                }

                Write($" {currentNode.data} ");
            }
        }
예제 #2
0
        static void Main(string[] args)
        {
            WriteLine("BST Creation & Iterative Traversal");
            WriteLine();

            WriteLine("Space & Time Complexity:");
            WriteLine("Traversal Time: O(n) & Space: O(n)");

            BST root = null;

            BST bst = new BST();

            root = bst.Insert(root, 20);
            root = bst.Insert(root, 2);
            root = bst.Insert(root, 10);
            root = bst.Insert(root, 25);
            root = bst.Insert(root, 60);
            // root = bst.Insert(root, -1);
            // root = bst.Insert(root,125);
            // root = bst.Insert(root,160);
            // root = bst.Insert(root, 11);

            // Given Nodes
            Write("Given Nodes: ");
            Write("20 2 10 25 60 -1");

            WriteLine();
            WriteLine();

            // Tree Traversal via In-Order
            Write("In-Order Traversal:   (L, RN, R) ");
            bst.InOrderTraversal(root);

            WriteLine();
            WriteLine();

            // Tree Traversal via Out-Order
            Write("Out-Order Traversal:  (R, RN, L) ");
            bst.OutOrderTraversal(root);

            WriteLine();
            WriteLine();

            // Tree Traversal via Pre-Order
            Write("Pre-Order Traversal:  (RN, L, R) ");
            bst.preOrderTraversal(root);

            WriteLine();
            WriteLine();

            // Tree Traversal via Post-Order
            Write("Post-Order Traversal: (L, R, RN) ");
            bst.postOrderTraversal(root);

            WriteLine();
            WriteLine();

            WriteLine($"Height of Tree: {bst.Height(root)}");

            WriteLine();
            WriteLine();
        }