LeetCode 98 Validate Binary Search Tree

LeetCode 98 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:

1 The left subtree of a node contains only nodes with keys less than the node's key.
2 The right subtree of a node contains only nodes with keys greater than the node's key.
3 Both the left and right subtrees must also be binary search trees.

要理解bst的以上3点性质,一般bst的遍历,都需要保存一个interval,保证该bst子树的所有node的值都在interval范围内!!!

代码:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public boolean isValidBST(TreeNode root) {
        return isValidRecursive(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    
    public boolean isValidRecursive(TreeNode root, long min, long max) {
        return root == null ||
        root.val < max && root.val > min && 
        isValidRecursive(root.left, min, root.val) && isValidRecursive(root.right, root.val, max);
    }
    
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容