Java implementation LeetCode 98 verified binary search tree

98. Verify binary search tree

Given a binary tree to determine if it is a valid binary search tree.

Suppose a binary search tree having the following characteristics:

Left child node of the tree contains only less than the current node number.
Right subtree contain only greater than the number of nodes of the current node.
All left subtree and right subtree itself must also be binary search tree.
Example 1:

Input:

    2
   / \
  1   3

Output: true
Example 2:

Input:

    5
   / \
  1   4
     / \
    3   6

Output: false
interpretation: Input as: [5,1,4, null, null, 3,6].
5 is a root node, but it is the right child node 4.

 
class Solution {
     double last = -Double.MAX_VALUE;
    public boolean isValidBST(TreeNode root) {
        if (root == null) {
            return true;
        }
        if (isValidBST(root.left)) {
            if (last < root.val) {
                last = root.val;
                return isValidBST(root.right);
            }
        }
        return false;
    }
}
Released 1214 original articles · won praise 10000 + · Views 650,000 +

Guess you like

Origin blog.csdn.net/a1439775520/article/details/104374446