【LeetCode】No.98. Validate Binary Search Tree -- Java Version

101 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第17天,点击查看活动详情.

题目链接:leetcode.com/problems/va…

1. 题目介绍(Validate Binary Search Tree)

Given the root of a binary tree, determine if it is a valid binary search tree (BST).

【Translate】: 给定二叉树的根,确定它是否是有效的二叉搜索树(BST)。

A valid 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.

【Translate】: 有效的BST定义如下:

  • 节点的左子树只包含键值小于该节点键值的节点。
  • 节点的右子树只包含键值大于该节点键值的节点。
  • 左子树和右子树都必须是二叉搜索树。

【测试用例】: tesecase1 tesecase2

【条件约束】:

Constraints

2. 题解

2.1 中序遍历栈

原题解来自于 issac3 的 Learn one iterative inorder traversal, apply it to multiple tree questions (Java Solution).

该题解的做法和 【LeetCode】No.94. Binary Tree Inorder Traversal -- Java Version中实现中序遍历的代码基本一致,不同点是在于多了一个前后节点大小比较的过程。

/**
 * 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) {
       if (root == null) return true;
       Stack<TreeNode> stack = new Stack<>();
       TreeNode pre = null;
       while (root != null || !stack.isEmpty()) {
          while (root != null) {
             stack.push(root);
             root = root.left;
          }
          root = stack.pop();
          if(pre != null && root.val <= pre.val) return false;
          pre = root;
          root = root.right;
       }
       return true;       
    }     
}

act1

2.2 递归

原题解来自于 sruzic 的 My simple Java solution in 3 lines.

/**
 * 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 isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }
    
    public boolean isValidBST(TreeNode root, long minVal, long maxVal) {
        if (root == null) return true;
        if (root.val >= maxVal || root.val <= minVal) return false;
        return isValidBST(root.left, minVal, root.val) && isValidBST(root.right, root.val, maxVal);
    } 
}

act2