# 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.

## Python: Tips of the Day

**Joining Collection:**

name = ["Owen", "Eddie"] print(" ".join(name))

Owen Eddie

**Weekly Trends**- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook