Example #1
0
        private static ResultNodes _CorrectBSTUtil(BinaryTreeNode binaryTreeNode, ResultNodes resultNodes)
        {
            if (binaryTreeNode == null)
            {
                return(resultNodes);
            }

            resultNodes = _CorrectBSTUtil(binaryTreeNode.GetLeftNode(), resultNodes);

            if (resultNodes != null &&
                resultNodes.GetPreviousNode() != null &&
                resultNodes.GetPreviousNode().GetData() > binaryTreeNode.GetData())
            {
                if (resultNodes.GetFirstNode() == null)
                {
                    resultNodes.SetFirstNode(resultNodes.GetPreviousNode());
                    resultNodes.SetSecondNode(binaryTreeNode);
                }
                else
                {
                    resultNodes.SetThirdNode(binaryTreeNode);
                }
            }

            if (resultNodes != null)
            {
                resultNodes.SetPreviousNode(binaryTreeNode);
            }
            BSTNodes++;
            return(_CorrectBSTUtil(binaryTreeNode.GetRightNode(), resultNodes));
        }
Example #2
0
        public static void CorrectBST(BinaryTreeNode binaryTreeNode)
        {
            ResultNodes resultNodes = new ResultNodes();

            resultNodes = _CorrectBSTUtil(binaryTreeNode, resultNodes);
            if (resultNodes == null)
            {
                Console.WriteLine("The entered Binary Search Tree is correct! No incorrect nodes found!");
            }
            else
            {
                if (resultNodes.GetThirdNode() != null)
                {
                    binaryTreeNode = RectifyTree(binaryTreeNode, resultNodes.GetFirstNode().GetData(),
                                                 resultNodes.GetThirdNode().GetData());
                }
                else
                {
                    binaryTreeNode = SwapAndRectify(binaryTreeNode, resultNodes.GetFirstNode(), resultNodes.GetSecondNode());
                }
                Console.WriteLine("-----Printing the rectified tree!---------");
                PrintTree(binaryTreeNode);
            }
        }