Beispiel #1
0
        private static void Main()
        {
            Console.WriteLine("Represents the following tree");
            Console.WriteLine(@"             4             ");
            Console.WriteLine(@"            / \            ");
            Console.WriteLine(@"           /   \           ");
            Console.WriteLine(@"          /     \          ");
            Console.WriteLine(@"         /       \         ");
            Console.WriteLine(@"        2         6        ");
            Console.WriteLine(@"       / \       / \       ");
            Console.WriteLine(@"      /   \     /   \      ");
            Console.WriteLine(@"     /     \   /     \     ");
            Console.WriteLine(@"     1     3   5     7     ");
            var binaryTree = new BinaryTree<int>();
            binaryTree.Add(4);
            binaryTree.Add(2);
            binaryTree.Add(6);
            binaryTree.Add(1);
            binaryTree.Add(3);
            binaryTree.Add(5);
            binaryTree.Add(7);

            var preOrderTraversal = new PreOrderTraversal<int>();
            Console.Write("PreOrder: ");
            preOrderTraversal.Traverse(binaryTree.Root);
            Console.WriteLine();

            Console.Write("InOrder: ");
            var inOrderTraversal = new PreOrderTraversal<int>();
            inOrderTraversal.Traverse(binaryTree.Root);
            Console.WriteLine();

            Console.Write("PostOrder: ");
            var postOrderTraversal = new PostOrderTraversal<int>();
            postOrderTraversal.Traverse(binaryTree.Root);
            Console.WriteLine();

            Console.WriteLine("Value to find: 5");
            Node<int> nodeFound = binaryTree.Find(5);

            if (nodeFound == null)
                Console.WriteLine("Value not found");
            else
                Console.WriteLine("Value found: {0}", nodeFound.Value);
            Console.WriteLine();

            Console.WriteLine("Value to find: 100");
            Node<int> notFound = binaryTree.Find(100);
            Console.WriteLine(notFound == null ? "Worked as expected" : "Failed");
        }
        static void Main()
        {
            var tree =
                new Tree<int>(7,
                    new Tree<int>(19,
                        new Tree<int>(1),
                        new Tree<int>(12),
                        new Tree<int>(31)),
                    new Tree<int>(21),
                    new Tree<int>(14,
                        new Tree<int>(23),
                        new Tree<int>(6)));

            Console.WriteLine("Tree (indented):");
            tree.Print();

            Console.Write("Tree nodes:");
            tree.Each(c => Console.Write(" " + c));
            Console.WriteLine();

            Console.WriteLine();

            var binaryTree =
                new BinaryTree<string>("*",
                    new BinaryTree<string>("+",
                        new BinaryTree<string>("3"),
                        new BinaryTree<string>("2")),
                    new BinaryTree<string>("-",
                        new BinaryTree<string>("9"),
                        new BinaryTree<string>("6")));

            Console.WriteLine("Binary tree (indented, pre-order):");
            binaryTree.PrintIndentedPreOrder();

            Console.Write("Binary tree nodes (in-order):");
            binaryTree.EachInOrder(c => Console.Write(" " + c));
            Console.WriteLine();

            Console.Write("Binary tree nodes (post-order):");
            binaryTree.EachPostOrder(c => Console.Write(" " + c));
            Console.WriteLine();
        }
Beispiel #3
0
        public static void driver()
        {
            BinaryTree tree = new BinaryTree();
            Console.WriteLine("Tree Traversals: \n\nInorder traversal recursive: ");
            tree.inorderRecur(tree.root);
            tree.inorderIter(tree.root);
            tree.inorderMorris(tree.root);

            Console.WriteLine("\nInorder successor = {0}", tree.inorderSuccBST(tree.root.left.right.right));
            Console.WriteLine("Inorder predecessor = {0}", tree.inorderPredBST(tree.root.left.right.right.left));

            Console.WriteLine("\n\nPreorder traversal recursive: ");
            tree.preorderRecur(tree.root);
            tree.preorderIter(tree.root);
            tree.preorderMorris(tree.root);

            Console.WriteLine("\nPreorder successor = {0}", tree.preorderSuccBST(tree.root.left.left));
            Console.WriteLine("Preorder predecessor = {0}", tree.preorderPredBST(tree.root));

            Console.WriteLine("\n\nPostorder traversal recursive: ");
            tree.postorderRecur(tree.root);
            tree.postorderIter(tree.root);
            tree.postorderIterOneStack(tree.root);

            Console.WriteLine("\n\nLevelorder traversal: ");
            tree.levelorder(tree.root);

            int[] pre = {6, 2, 1, 3, 5, 4, 8, 7, 10, 9};
            int[] inorder = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
            int preIndex = 0;
            Node inpreNode = tree.InPreToBinaryTree(pre, inorder, 0, inorder.Length - 1, ref preIndex);
            Console.WriteLine("\nNewly constructed tree from inorder and preorder traversals: ");
            tree.levelorder(inpreNode);

            Console.WriteLine("\nSorted Array to Balanced BST: ");
            Node arrToBSTNode = tree.SortedArrToBinaryTree(inorder, 0, inorder.Length - 1);
            tree.levelorder(arrToBSTNode);
        }
Beispiel #4
0
        public static void Main(string[] args)
        {
            // Declare placeholder variables - used later by various methods
            string menuSelection = "", newNodeInput = "", nodeSearchValue = "";

            // Instantiate BinaryTree and BinarySearchTree objects, add initial values
            BinaryTree binTree = new BinaryTree(new Node(25));

            binTree.Add(binTree.Root, new Node(10));
            binTree.Add(binTree.Root, new Node(5));
            binTree.Add(binTree.Root, new Node(7));
            binTree.Add(binTree.Root, new Node(1));
            binTree.Add(binTree.Root, new Node(40));
            binTree.Add(binTree.Root, new Node(50));
            binTree.Add(binTree.Root, new Node(30));

            BinarySearchTree binSearchTree = new BinarySearchTree(new Node(25));

            binSearchTree.Add(binSearchTree.Root, new Node(10));
            binSearchTree.Add(binSearchTree.Root, new Node(5));
            binSearchTree.Add(binSearchTree.Root, new Node(7));
            binSearchTree.Add(binSearchTree.Root, new Node(1));
            binSearchTree.Add(binSearchTree.Root, new Node(40));
            binSearchTree.Add(binSearchTree.Root, new Node(50));
            binSearchTree.Add(binSearchTree.Root, new Node(30));

            // Loop until the user enters the "8" key to exit the application
            do
            {
                // Prompt user to select an option from the menu
                PrintMainMenu();
                menuSelection = Console.ReadLine();
                Console.Clear();

                switch (menuSelection)
                {
                case "1":     // Adds a Node to the Binary Tree
                    Console.WriteLine("What value you like add to the Binary Tree?");
                    newNodeInput = Console.ReadLine();
                    Console.Clear();

                    if (int.TryParse(newNodeInput, out int binTree_Add))
                    {
                        binTree.Add(binTree.Root, new Node(binTree_Add));
                        Console.WriteLine("Success!");
                    }
                    else
                    {
                        Console.WriteLine("Sorry, unable to add that value to the Binary Tree.");
                    }

                    PromptToReturnToMainMenu();
                    break;

                case "2":     // Adds a Node to the Binary Search Tree
                    Console.WriteLine("What value you like add to the Binary Search Tree?");
                    newNodeInput = Console.ReadLine();
                    Console.Clear();

                    if (int.TryParse(newNodeInput, out int binSearchTree_Add))
                    {
                        binSearchTree.Add(binSearchTree.Root, new Node(binSearchTree_Add));
                        Console.WriteLine("Success!");
                    }
                    else
                    {
                        Console.WriteLine("Sorry, unable to add that value to the Binary Search Tree.");
                    }

                    PromptToReturnToMainMenu();
                    break;

                case "3":     // Searches for a value in the Binary Tree
                    Console.WriteLine("What value you like search for in the Binary Tree?");
                    nodeSearchValue = Console.ReadLine();
                    Console.Clear();

                    if (int.TryParse(nodeSearchValue, out int binTree_Search))
                    {
                        Node foundBinTreeNode = binTree.Search(binTree.Root, binTree_Search);

                        if (foundBinTreeNode != null)
                        {
                            Console.WriteLine("Found!");
                        }
                        else
                        {
                            Console.WriteLine("That value does not exist within the Binary Tree");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Sorry, please input an integer to search for.");
                    }

                    PromptToReturnToMainMenu();
                    break;

                case "4":     // Searches for a value in the Binary Search Tree
                    Console.WriteLine("What value you like search for in the Binary Search Tree?");
                    nodeSearchValue = Console.ReadLine();
                    Console.Clear();

                    if (int.TryParse(nodeSearchValue, out int binSearchTree_Search))
                    {
                        Node foundBinSearchTreeNode = binSearchTree.Search(binSearchTree.Root, binSearchTree_Search);

                        if (foundBinSearchTreeNode != null)
                        {
                            Console.WriteLine("Found!");
                        }
                        else
                        {
                            Console.WriteLine("That value does not exist within the Binary Search Tree");
                        }
                    }
                    else
                    {
                        Console.WriteLine("Sorry, please input an integer to search for.");
                    }

                    PromptToReturnToMainMenu();
                    break;

                case "5":     // Prints the values in the Binary Tree in "Preorder" sequence
                    binTree.PreOrder(binTree.Root);

                    PromptToReturnToMainMenu();
                    break;

                case "6":     // Prints the values in the Binary Tree in "Postorder" sequence
                    binTree.PostOrder(binTree.Root);

                    PromptToReturnToMainMenu();
                    break;

                case "7":     // Prints the values in the Binary Tree in "Inorder" sequence
                    binTree.InOrder(binTree.Root);

                    PromptToReturnToMainMenu();
                    break;

                case "8":     // Prints the values in the Binary Tree in "Breadth First" sequence
                    binTree.BreadthFirst(binTree.Root);

                    PromptToReturnToMainMenu();
                    break;

                case "9":     // Exits the Program
                    Environment.Exit(0);
                    break;

                default:     // Handles cases where user doesn't enter a valid menu option
                    Console.WriteLine("That did not match one of the menu options. Try again.\n");
                    break;
                }
            } while (menuSelection != "9");
        }
 static void Main(string[] args)
 {
     BinaryTree.MyMain();
     Console.ReadLine();
 }
 public BinaryTree(int value)
 {
     this.value      = value;
     this.rightChild = null;
     this.leftChild  = null;
 }
        public static void TreeCarlos()
        {
            Node nodeOne   = new Node(1);
            Node nodeTwo   = new Node(2);
            Node nodeThree = new Node(3);
            Node nodeFour  = new Node(4);
            Node nodeFive  = new Node(5);
            Node nodeSix   = new Node(6);
            Node nodeSeven = new Node(7);
            Node nodeEight = new Node(8);
            Node nodeNine  = new Node(9);
            Node nodeTen   = new Node(10);

            BinaryTree binaryTree = new BinaryTree(nodeOne);

            binaryTree.Root.LeftChild             = nodeTwo;
            binaryTree.Root.RightChild            = nodeThree;
            binaryTree.Root.LeftChild.LeftChild   = nodeFour;
            binaryTree.Root.LeftChild.RightChild  = nodeFive;
            binaryTree.Root.RightChild.LeftChild  = nodeSix;
            binaryTree.Root.RightChild.RightChild = nodeSeven;

            Console.WriteLine(" ");
            Console.WriteLine("==========PreOrder=========");
            List <int> preOrder = binaryTree.PreOrder(binaryTree.Root);

            foreach (var item in preOrder)
            {
                Console.Write(item);
            }

            binaryTree.values.Clear();
            Console.WriteLine(" ");
            Console.WriteLine("==========InOrder=========");
            List <int> inOrder = binaryTree.InOrder(binaryTree.Root);

            foreach (var item in inOrder)
            {
                Console.Write(item);
            }

            binaryTree.values.Clear();
            Console.WriteLine(" ");
            Console.WriteLine("==========PostOrder=========");
            List <int> postOrder = binaryTree.PostOrder(binaryTree.Root);

            foreach (var item in postOrder)
            {
                Console.Write(item);
            }

            binaryTree.values.Clear();
            Console.WriteLine(" ");
            Console.WriteLine("==========Add Binary Search Tree=========");
            Console.WriteLine("Added 2, 3, 4, 6, 7, 8, 10");
            BinarySearchTree binarySearchTree = new BinarySearchTree();

            binarySearchTree.Add(nodeSix, 3);
            binarySearchTree.Add(nodeSix, 2);
            binarySearchTree.Add(nodeSix, 4);
            binarySearchTree.Add(nodeSix, 8);
            binarySearchTree.Add(nodeSix, 7);
            binarySearchTree.Add(nodeSix, 10);
            Console.WriteLine("==========Contains Binary Search Tree=========");
            Console.WriteLine($"Contains 7: {binarySearchTree.Contains(nodeSix, 4)}");
            Console.WriteLine($"Contains 52: {binarySearchTree.Contains(nodeSix, 52)}");
        }
Beispiel #8
0
 public static void PostOrder(BinaryTree tree)
 {
     PostOrder(tree.Root);
 }
Beispiel #9
0
        static void Main(string[] args)
        {
            BinaryTree tree = new BinaryTree();

            //BST insert
            /*                7
             *           4            10
             *       3      6      9      11
             *    1
             *      2
             *
             *
             * */
            tree.Insert(7);
            tree.Insert(10);
            tree.Insert(4);
            tree.Insert(6, isIterative: true);
            tree.Insert(9, isIterative: true);
            tree.Insert(11);
            tree.Insert(3);
            //tree.Insert(5);
            tree.Insert(1);
            tree.Insert(2);

            //Binary Tree Insert
            /*        7
             *     2      2
             *   3   3  3   3
             *
             * */
            //BinaryTree tree1 = new BinaryTree();
            //tree1.BinaryTreeInsert(7);
            //tree1.BinaryTreeInsert(2);
            //tree1.BinaryTreeInsert(2);
            //tree1.BinaryTreeInsert(3);
            //tree1.BinaryTreeInsert(3);
            //tree1.BinaryTreeInsert(3);
            //tree1.BinaryTreeInsert(3);

            //tree1.InorderTraversal(tree1.Root);
            //bool isSymmetric = tree1.isSymmetric();
            //Console.WriteLine("Is this tree symmetric?" + isSymmetric);

            //Test code
            //tree.Insert(10);
            //tree.Insert(9);
            //tree.Insert(11);
            //tree.Insert(8);

            //tree.InorderTraversal(tree.Root);

            BinaryTreeNode x = tree.Search(12, isIterative: true);
            if(x!=null)
            {
                Console.WriteLine("Found the element searching for.." + x.Key);
            }

            int height = tree.Height(isiterative: false);
            Console.WriteLine(height);

            bool isHeighBalanced = tree.IsHeightBalanced();
            Console.WriteLine("Is it a height balanced tree?" + isHeighBalanced);

            BinaryTreeNode kthInorderNode = null;
            int k = 10;
            tree.KthNodeInorder(ref kthInorderNode, k);
            if (kthInorderNode != null)
            {
                Console.WriteLine("the kth order node is " + kthInorderNode.Key);
            }

            //Binary tree to doubly linked list
            BinaryTreeNode visited = null;
            tree.BinaryTreeToDoublyLinkedList(ref visited);

            tree.PrintDoublyLinkedList(tree.Root);

            //LCA of Binary Tree
            //BinaryTreeNode lca = tree.LCA(3, 6);
            //if(lca!=null)
            //{
            //    Console.WriteLine("LCA of {0},{1} is {2}", 3, 6, lca.Key);
            //}

            // LCA of binary Search tree
            //BinaryTreeNode lca_bst = tree.LCA(2, 9);
            //if (lca_bst != null)
            //{
            //    Console.WriteLine("LCA of {0},{1} is {2}", 1, 2, lca_bst.Key);
            //}

            Console.ReadLine();
        }
Beispiel #10
0
 public static void InOrder(BinaryTree tree)
 {
     InOrder(tree.Root);
 }
Beispiel #11
0
        public static void Main(string[] args)
        {
            // First Child / Next Sibling Tree

            // Structure:
            //
            //          A
            //		  / | \ \
            //       B	C  D E
            //	    / \	   | | \
            //	   F   G   H I	J
            //					|
            //					K
            //

            Console.WriteLine("First Child / Next Sibling Tree:");
            var myFCNSTree = new FCNSTree <char>('A');

            myFCNSTree.Root.AddChild('B').AddChild('F').AddSibling('G');
            myFCNSTree.Root.AddChild('C');
            myFCNSTree.Root.AddChild('D').AddChild('H');
            myFCNSTree.Root.AddChild('E').AddChild('I').AddSibling('J').AddChild('K');
            myFCNSTree.PrintPreOrder();                                                       // A B F G C D H E I J K
            Console.WriteLine(myFCNSTree.Root);                                               // A
            Console.WriteLine(myFCNSTree.Root.FirstChild);                                    // B
            Console.WriteLine(myFCNSTree.Root.FirstChild.NextSibling.NextSibling.FirstChild); // H
            Console.WriteLine("--------------------------------------------------------------");


            // Binary Tree

            // Structure:
            //
            //		4
            //	   / \ 
            //	  2	  6
            //   / \
            //	1	3
            //

            Console.WriteLine("Binary Tree:");
            var myBinaryTree = new BinaryTree <int>(4);

            myBinaryTree.Root.AddLeftChild(2);
            myBinaryTree.Root.AddRightChild(6);
            myBinaryTree.Root.LeftChild.AddLeftChild(1);
            myBinaryTree.Root.LeftChild.AddRightChild(3);

            myBinaryTree.PrintPreOrder();               // 4 2 1 3 6
            myBinaryTree.PrintInOrder();                // 1 2 3 4 6
            myBinaryTree.PrintPostOrder();              // 1 3 2 6 4

            Console.WriteLine("Size: " + myBinaryTree.Size);
            Console.WriteLine("Height: " + myBinaryTree.Height);

            var newTree = new BinaryTree <int>(4);

            newTree.Root.AddLeftChild(2);
            newTree.Root.AddRightChild(6);

            myBinaryTree.Merge(12, myBinaryTree, newTree);
            Console.WriteLine("PrettyPrint: " + myBinaryTree);
            Console.WriteLine("--------------------------------------------------------------");


            // Binary Search Tree
            //
            // Structure:
            //
            //		6
            //	   / \ 
            //	  4	  7
            //   / \
            //	2	5
            //

            Console.WriteLine("Binary Search Tree:");
            var myBinarySearchTree = new BinarySearchTree.BinarySearchTree(6);

            myBinarySearchTree.Insert(4);
            myBinarySearchTree.Insert(7);
            myBinarySearchTree.Insert(2);
            myBinarySearchTree.Insert(5);

            Console.WriteLine("InOrder: " + myBinarySearchTree.InOrder());

            Console.WriteLine("RemoveMin()");
            myBinarySearchTree.Remove(2);

            Console.WriteLine("InOrder: " + myBinarySearchTree.InOrder());

            Console.WriteLine("FindMin: " + myBinarySearchTree.FindMin());
            Console.WriteLine("FindMax: " + myBinarySearchTree.FindMax());

            Console.WriteLine("PrettyPrint: " + myBinarySearchTree);
            Console.WriteLine("--------------------------------------------------------------");

            // Binary MinHeap

            Console.WriteLine("Binary MinHeap:");
            var myBinaryHeap = new BinaryMinHeap.BinaryMinHeap();

            myBinaryHeap.Insert(2);
            myBinaryHeap.Insert(10);
            myBinaryHeap.Insert(8);
            myBinaryHeap.Insert(1);
            myBinaryHeap.Insert(6);
            myBinaryHeap.Insert(9);

            Console.WriteLine("Heap: " + myBinaryHeap);

            Console.WriteLine("Value: " + myBinaryHeap.Value);

            Console.WriteLine("Removed: " + myBinaryHeap.Remove());
            Console.WriteLine("Removed: " + myBinaryHeap.Remove());

            Console.WriteLine("Value: " + myBinaryHeap.Value);

            Console.WriteLine("Removed: " + myBinaryHeap.Remove());
            Console.WriteLine("Removed: " + myBinaryHeap.Remove());

            Console.WriteLine("Value: " + myBinaryHeap.Value);

            Console.WriteLine("Heap: " + myBinaryHeap);
            Console.WriteLine("--------------------------------------------------------------");
        }
 public BinaryTree(T value, BinaryTree <T> leftChild = null, BinaryTree <T> rightChild = null)
 {
     this.Value = value;
     this.Left  = leftChild;
     this.Right = rightChild;
 }
Beispiel #13
0
        public bool remove(T val)
        {
            //Проверяем, существует ли данный узел
            BinaryTree <T> tree = search(val);

            if (tree == null)
            {
                //Если узла не существует, вернем false
                return(false);
            }
            BinaryTree <T> curTree;

            //Если удаляем корень
            if (tree == this)
            {
                if (tree.right != null)
                {
                    curTree = tree.right;
                }
                else
                {
                    curTree = tree.left;
                }

                while (curTree.left != null)
                {
                    curTree = curTree.left;
                }
                T temp = curTree.val;
                this.remove(temp);
                tree.val = temp;

                return(true);
            }

            //Удаление листьев
            if (tree.left == null && tree.right == null && tree.parent != null)
            {
                if (tree == tree.parent.left)
                {
                    tree.parent.left = null;
                }
                else
                {
                    tree.parent.right = null;
                }
                return(true);
            }

            //Удаление узла, имеющего левое поддерево, но не имеющее правого поддерева
            if (tree.left != null && tree.right == null)
            {
                //Меняем родителя
                tree.left.parent = tree.parent;
                if (tree == tree.parent.left)
                {
                    tree.parent.left = tree.left;
                }
                else if (tree == tree.parent.right)
                {
                    tree.parent.right = tree.left;
                }
                return(true);
            }

            //Удаление узла, имеющего правое поддерево, но не имеющее левого поддерева
            if (tree.left == null && tree.right != null)
            {
                //Меняем родителя
                tree.right.parent = tree.parent;
                if (tree == tree.parent.left)
                {
                    tree.parent.left = tree.right;
                }
                else if (tree == tree.parent.right)
                {
                    tree.parent.right = tree.right;
                }
                return(true);
            }

            //Удаляем узел, имеющий поддеревья с обеих сторон
            if (tree.right != null && tree.left != null)
            {
                curTree = tree.right;

                while (curTree.left != null)
                {
                    curTree = curTree.left;
                }

                //Если самый левый элемент является первым потомком
                if (curTree.parent == tree)
                {
                    curTree.left     = tree.left;
                    tree.left.parent = curTree;
                    curTree.parent   = tree.parent;
                    if (tree == tree.parent.left)
                    {
                        tree.parent.left = curTree;
                    }
                    else if (tree == tree.parent.right)
                    {
                        tree.parent.right = curTree;
                    }
                    return(true);
                }
                //Если самый левый элемент НЕ является первым потомком
                else
                {
                    if (curTree.right != null)
                    {
                        curTree.right.parent = curTree.parent;
                    }
                    curTree.parent.left = curTree.right;
                    curTree.right       = tree.right;
                    curTree.left        = tree.left;
                    tree.left.parent    = curTree;
                    tree.right.parent   = curTree;
                    curTree.parent      = tree.parent;
                    if (tree == tree.parent.left)
                    {
                        tree.parent.left = curTree;
                    }
                    else if (tree == tree.parent.right)
                    {
                        tree.parent.right = curTree;
                    }

                    return(true);
                }
            }
            return(false);
        }
Beispiel #14
0
 public BinaryTree(T val, BinaryTree <T> parent)
 {
     this.val    = val;
     this.parent = parent;
 }