DFS

Validate Binary Search Tree

Link: https://leetcode.com/problems/validate-binary-search-tree/

Code:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        return validate(root, null, null);
    }
    
    boolean validate(TreeNode node, Integer low, Integer high) {
        // empty trees are valid
        if (node == null) return true;
        // current node's value must be between low and high.
        if ((low != null && node.val <= low) || (high != null && node.val >= high)) {
            return false;
        }
        return validate(node.right, node.val, high) && validate(node.left, low, node.val);
    }
}
  • Why parameter low and high type is Integer instead of int?

    • Because we need to pass null to the function

    • If we use int, we will get compile error.

Recover Binary Search Tree

Link: https://leetcode.com/problems/recover-binary-search-tree/

Code:

The recursive inorder traversal approach:

Different DFS strategy:

DFS strategy

Last updated