182k views
4 votes
Validate Binary Search Tree.

Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:

a) The left subtree of a node contains only nodes with keys less than the node's key.
b) The right subtree of a node contains only nodes with keys greater than the node's key.
c) Both the left and right subtrees must also be binary search trees.

User Scrimau
by
8.2k points

1 Answer

6 votes

Final answer:

To validate a binary search tree, one must verify that each node has its left subtree containing only nodes with lesser values, its right subtree only containing nodes with greater values, and that this condition is met for all subtrees within the tree through recursion.

Step-by-step explanation:

The question of whether a binary tree is a valid binary search tree (BST) is one that involves checking a series of conditions that apply to all nodes in the tree. To determine the validity of a BST, one must adhere to the definition and properties of a BST. According to the definition provided:

  • The left subtree of a node contains only nodes with keys less than the node's key.
  • The right subtree of a node contains only nodes with keys greater than the node's key.
  • Both the left and right subtrees must also be binary search trees.

To validate this, a recursive approach is often used, where the function traverses the tree and checks these properties at each node. A helper function can be designed to pass not just the node, but also a range of valid values for that node, which gets narrower as you go down the tree. For the initial call to this helper function, the valid range can be set from negative infinity to positive infinity.

The recursive function will do the following:

  1. Check if the current node is null. If it's null return true, as an empty tree is a valid BST.
  2. Check if the value of the current node is within the valid range (less than the higher bound and greater than the lower bound).
  3. Recursively validate the left subtree with an updated upper bound as the current node's value.
  4. Recursively validate the right subtree with an updated lower bound as the current node's value.

If at any point a violation of the conditions is found, the function should return false. If the end of the tree is reached without finding any violations, the tree is a valid BST. It is important to check each node and its subtrees for the BST properties to ensure the whole tree is valid.

Example: Consider a node with a value of 10, the nodes in its left subtree should be less than 10, and the nodes in the right subtree should be greater than 10 for it to be a valid BST. This would be recursively validated for every node.

User Birdus
by
8.0k points