98. Validate Binary Search Tree (Medium)
https://leetcode.com/problems/validate-binary-search-tree/
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.
Example 1:
Input: 2 / \ 1 3 Output: true
Example 2:
5 / \ 1 4 / \ 3 6 Output: false Explanation: The input is: [5,1,4,null,null,3,6]. The root node's value is 5 but its right child's value is 4.
Solutions
class Solution {
// Actually, the best solution is to traverse the tree and return the visiting sequence.
// Then sort out if the outcome is sorted by ascending order or not. If not well ordered,
// this tree must not be the valid Binary Sort Tree.
public boolean isValidBST(TreeNode root) {
List<Integer> track = new ArrayList<>();
traverse(root, track);
for (int i = 1; i < track.size(); i++) {
if (track.get(i - 1) >= track.get(i)) {
return false;
}
}
return true;
}
private void traverse(TreeNode root, List<Integer> track) {
if (root == null) {
return;
}
traverse(root.left, track);
track.add(root.val);
traverse(root.right, track);
}
}
Incorrect Solutions
class Solution2 {
// This solution is trivial, nasty and incorrect.
// You can look into this test case: [3,1,5,0,2,4,6,null,null,null,3] and will
// find out what's going wrong here.
public boolean isValidBST(TreeNode root) {
if (root == null) {
return true;
}
return check(root, "", root.val);
}
private boolean check(TreeNode root, String from, int limit) {
if (root == null) {
return true;
}
// 1 Make sure the value order is left < root < right = is also not permitted
if (root.left != null && root.left.val >= root.val) {
return false;
}
if (root.right != null && root.right.val <= root.val) {
return false;
}
// 2.1 If this branch is the left one of parent, this.right.val < parent.val;
if (from.equals("left") && root.right != null && root.right.val >= limit) {
return false;
}
// 2.2 If this branch is the right one of parent, this.left.val > parent.val;
if (from.equals("right") && root.left != null && root.left.val <= limit) {
return false;
}
// If left branch is invalid, not need to validate right branch, return immediately.
if (!check(root.left, "left", root.val)) {
return false;
}
if (!check(root.right, "right", root.val)) {
return false;
}
return true;
}
}