二刷98. Validate Binary Search Tree

Medium
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:

    2
   / \
  1   3

Binary tree [2,1,3], return true.

Example 2:

    1
   / \
  2   3

Binary tree [1,2,3], return false.

二刷还是看答案做出来的,这道题有几个坑:

  • root的val可能超出Integer的范围,比如有一个test case给的root.val = 2147483647
  • 要注意BST的定义里,每个节点左边的子数val必须小于该节点,右边的子树必须大于该节点。不只是直接的left, right, 而是左边所有的、右边所有的,这个概念可能会有模糊理解
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        if (root == null){
            return true;
        }
        return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    
    private boolean helper(TreeNode root, long low, long high){
        if (root.val <= low || root.val >= high){
            return false;
        }
        if (root.left != null && !helper(root.left, low, root.val)){
            return false;
        }
        if (root.right != null && !helper(root.right, root.val, high)){
            return false;
        }
        return true;
    }
}

这道题还可以用inorder traversal做:


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容