What are the "min" and "max" in this function to check if the binary tree is a valid BST?

Below is the binary tree search code in the binary search tree .

bool IsValidBST(BinaryNode node, int MIN, int MAX) 
{
     if(node == null)
     return true;

    if(node.element > MIN 
         && node.element < MAX
         && IsValidBST(node.left,MIN,node.element)
         && IsValidBST(node.right,node.element,MAX))
         return true;
     else 
         return false;
}

How are used here MINand MAX? What meanings do they represent? And why do they need to go through a function?

+5
source share
4 answers

[MIN, MAX] , node. node INT_MIN INT_MAX, , BST - node . MIN MAX .

. , :

 if(node.element >= MIN 
   && node.element <= MAX
   && IsValidBST(node.left,MIN,node.element)
   && IsValidBST(node.right,node.element,MAX))

.

+6

, , .

, MIN MAX , .

0

MIN MAX , , , .

I think simplest way to check the valid BST tree is traverse inorder and check if
the values are in sorted order or not? if all the values are in sorted order that
means its valid BST.

http://justprogrammng.blogspot.com/2012/06/check-if-tree-is-bst-on-code-interview.html

0

, . INT_MIN INT_MAX .

IsValidBST (root, INT_MIN, INT_MAX)

. , , MIN MAX, .

, BT BST , . 1. node 2. .

, .

#define MIN (FirstVal, SecondVal) ((FirstVal) < (SecondVal)) ? (FirstVal):(SecondVal)
#define MAX (FirstVal, SecondVal) ((FirstVal) > (SecondVal)) ? (FirstVal):(SecondVal)

template <class T>
bool IsValidBST (treeNode &root)
{

   T min,  max;
   return IsValidBST (root, &min, &max);
}

template <class T>
bool IsValidBST (treeNode *root, T *MIN , T *MAX)
{
   T leftMin, leftMax, rightMin, rightMax;
   bool isValidBST;

   if (root->leftNode == NULL && root->rightNode == NULL)
   {
      *MIN = root->element;
      *MAX = root->element;
      return true;
   }

  isValidBST = IsValidBST (root->leftNode, &leftMin, &leftMax);

  if (isValidBST)
    isValidBST = IsValidBST (root->rightNode, &rightMin, &rightMax);

  if (isValidBST)
  {
     *MIN = MIN (leftMIN, rightMIN);
     *Max = MAX (rightMax, leftMax);
  }

  return isValidBST;
}
0

All Articles