Finding the largest subtree in a BST

前端 未结 9 746
别那么骄傲
别那么骄傲 2020-12-28 11:02

Given a binary tree, I want to find out the largest subtree which is a BST in it.

Naive approach:

I have a naive approach in mind where I visit every node of

9条回答
  •  旧巷少年郎
    2020-12-28 11:20

    I would think you could avoid checking if every node is the root of a BST by working top down instead of bottom up. If a subtree is a BST it's going to be larger than any subtree in itself so you don't need to check inside a subtree if it has passed the isBST test. Then you just have isBST return the size of a valid tree and store that along with a pointer to the root of the subtree if you need to be able to find it again instead of just knowing how large the largest one is.

    UPDATE:

    Some of the code posted here to check if something is a BST are going to fail some cases since they're only checking the parent of a node.

    Take for example:

           10
         /    \
       4      99
              /
             2
    

    This is not a valid BST, (the 2 is out of position with regards to the 10) but if you don't send a min and max value down through the tree you will incorrectly verify it as valid. This pseudocode takes that into account.

    main
    {
        Verify(root, MIN_VALUE, MAX_VALUE)
    }
    
    boolean Verify(node , min, max)
    {
    
     if(node == null)
       return true;
    
      if(node.value > min &&
         node.value < max &&
         Verify(node.leftchild, min, node.value) &&
         Verify(node.rightchild,node.value,max)
      {
          return true;
      }
      else
      {
          return false;
      }
    }
    

提交回复
热议问题