For a given binary tree find maximum binary search sub-tree

前端 未结 7 1993
南旧
南旧 2021-02-02 17:34

For a given binary tree, find the largest subtree which is also binary search tree?

Example:

Input:

                   10
               /                


        
7条回答
  •  无人共我
    2021-02-02 17:52

    GetLargestSortedBinarySubtree(thisNode, ref OverallBestTree)
        if thisNode == null
            Return null
        LeftLargest = GetLargestSortedBinarySubtree(thisNode.LeftNode, ref OverallBestTree)
        RightLargest = GetLargestSortedBinarySubtree(thisNode.RightNode, ref OverallBestTree)
        if LeftLargest.Max < thisNode.Value & RightLargest.Min > thisNode.Value
            currentBestTree = new BinaryTree(LeftLargest, thisNode.Value, RightLargest)
        else if LeftLargest.Max < thisNode.Value
            currentBestTree = new BinaryTree(LeftLargest, thisNode.Value, null)
        else if RightLargest.Min > thisNode.Value
            currentBestTree = new BinaryTree(null, thisNode.Value, RightLargest)
        else
            currentBestTree = new BinaryTree(null, thisNode.Value, null)
        if (currentBestTree.Size > OverallBestTree.Size)
            OverallBestTree = currentBestTree
        return currentBestTree
    

    As BlueRaja pointed out, this algorithm is not correct.

    It should really be called GetLargestSortedBinarySubtreeThatCanBeRecursivelyConstructedFromMaximalSortedSubtrees.

提交回复
热议问题