Problem Summary
Given a binary tree, determine if it is a binary search tree.
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.
- A single node tree is a BST.
Solution 1
We can use DFS to check whether the tree is a BST.
For each node, we use its value to determine the maximum value of its left subtree and the minimum value of its right subtree.
Solution 2
Since the BST required in this problem should not contain duplicate values, we can do an inorder traversal, and if the sequence is stictly increasing, the tree is a BST.
Code for Solution 1
|
|