Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a 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.
For checking the property of every node in search tree, we recursive traverse all the nodes.
We use a
rec helper function with two more extra parameters as the left bounder and right bounder node.
Traverse binary tree with inorder
For the property of BST, if we traverse the tree in the
inorder, it will be a increasing sequence. Add a varaible name of
pre to store the previous tree node.
If it is not a valid binary search tree, this property will not hold.
We can also use a
stack to implement a iteractive algorithm:
Join my Email List for more helpful insights, It's Free!😋