← Whiteboard questions

Check that a tree is a valid search tree

DSA, Medium

Which structure or algorithm, and what does it cost.

A binary tree is a search tree when, for every node, all values in its left subtree are smaller than the node and all values in its right subtree are larger. Equal values are not allowed. You get the root of a binary tree. Each node has val, left and right, and left or right is null when absent. Return true if the tree is a valid search tree, and false if not. An empty tree (root is null) is valid.

Examples

Input tree level by level: 8 / (4, 12) / (2, 6, 10, 14)
Output true
Why Every node is larger than everything on its left and smaller than everything on its right.
Input tree level by level: 8 / (4, 12) / (-, -, 7, 14)
Output false
Why 7 is the left child of 12, so it is right of 8, but 7 < 8. Each parent-child pair looks fine; the rule fails further up.
Input tree: 5 with a left child 5
Output false
Why Edge case: equal values are not allowed.

Constraints

Your answer must contain

Check that a tree is a valid search tree · OpsKarma