# Python Binary Search Tree: Check a binary tree is valid or not

## Python Binary Search Tree: Exercise-3 with Solution

Write a Python program to check whether a given binary tree is a valid binary search tree (BST) or not.

Let a binary search tree (BST) is defined as follows:

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.

Example 1: 2 / \ 1 3 Binary tree [2,1,3], return true. Example 2: 1 / \ 2 3 Binary tree [1,2,3], return false.

**Sample Solution**:

**Python Code:**

```
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def is_BST(root):
stack = []
prev = None
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
if prev and root.val <= prev.val:
return False
prev = root
root = root.right
return True
root = TreeNode(2)
root.left = TreeNode(1)
root.right = TreeNode(3)
result = is_BST(root)
print(result)
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
result = is_BST(root)
print(result)
```

Sample Output:

True False

**Flowchart: **

**Python Code Editor:**

** Contribute your code and comments through Disqus.**

**Previous:** Write a Python program to find the closest value of a given target value in a given non-empty Binary Search Tree (BST) of unique values.

**Next:** Write a Python program to delete a node with the given key in a given Binary search tree (BST).

**What is the difficulty level of this exercise?**

Test your Programming skills with w3resource's quiz.

**Weekly Trends and Language Statistics**- Weekly Trends and Language Statistics