Exemplo n.º 1
0
        public static BinaryTree ModifyTree(BinaryTree binaryTree)
        {
            if (binaryTree == null)
            {
                Console.WriteLine("Input BST is null. There is nothing to modify!");
                return(null);
            }

            Console.WriteLine("Modifying Root Node with the first Node in left Tree");
            try
            {
                if (binaryTree != null)
                {
                    int value1 = binaryTree.GetRootNode() != null?
                                 binaryTree.GetRootNode().GetData() : -1;

                    int value2 = binaryTree.GetRootNode().GetLeftNode() != null?
                                 binaryTree.GetRootNode().GetLeftNode().GetData() : -1;

                    int value3 = binaryTree.GetRootNode().GetRightNode() != null?
                                 binaryTree.GetRootNode().GetRightNode().GetData() : -1;

                    if (value1 != -1 && value2 != -1)
                    {
                        binaryTree.GetRootNode().SetData(value2);
                        binaryTree.GetRootNode().GetLeftNode().SetData(value1);
                    }
                    else if (value1 != -1 && value3 != -1)
                    {
                        binaryTree.GetRootNode().SetData(value3);
                        binaryTree.GetRootNode().GetRightNode().SetData(value1);
                    }
                    Console.WriteLine("Modified BST is -----------");
                    TreeUtility.PrintTree(binaryTree.GetRootNode());
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("Thrown exception is " + exception.Message);
            }
            return(binaryTree);
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            Console.WriteLine("Correct a BST whose two nodes are swapped!");
            Console.WriteLine("------------------------------------------");

            BinaryTree binaryTree = ConstructTree();

            try
            {
                Console.WriteLine("The input BST----------");
                TreeUtility.PrintTree(binaryTree.GetRootNode());
                Console.WriteLine();
                binaryTree = TreeUtility.ModifyTree(binaryTree);
                Console.WriteLine();
                TreeUtility.CorrectBST(binaryTree.GetRootNode());
            }
            catch (Exception exception) {
                Console.WriteLine("Thrown exception is " + exception.Message);
            }
            Console.ReadLine();
        }