2
头图

Verify binary search tree

Title description: Given a binary tree, judge whether it is a valid binary search tree.

Suppose a binary search tree has the following characteristics:

  • The left subtree of the node only contains numbers less than the current node.
  • The right subtree of the node only contains numbers greater than the current node.
  • All left subtrees and right subtrees themselves must also be binary search trees.

Please refer to LeetCode official website for example description.

Source: LeetCode
Link: https://leetcode-cn.com/problems/validate-binary-search-tree/
The copyright belongs to Lingkou Network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

Solution one: recursive method

According to the nature of the binary search tree, the upper boundary (not included) of the left subtree of the current node and the lower boundary (not included) of the right subtree are the value of the current node, so it can be solved by a recursive method. The recursive process is as follows:

  • The root node has no parent node, so the upper and lower boundaries of the recursive method are called the maximum and minimum values for the first time;
  • If the current node is null, it means it is a leaf node, and directly returns true;
  • If the value of the current node is not within the upper and lower bounds, false is returned;
  • Recursively judge whether the left and right nodes of the current node are within the corresponding upper line boundary.
import com.kaesar.leetcode.TreeNode;

public class LeetCode_098 {
    /**
     * 递归法
     *
     * @param root
     * @return
     */
    public static boolean isValidBST(TreeNode root) {
        return isValidBST(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    /**
     * 递归方法
     *
     * @param node 当前节点
     * @param low  当前节点的下边界(不包含)
     * @param high 当前节点的上边界(不包含)
     * @return
     */
    private static boolean isValidBST(TreeNode node, long low, long high) {
        // 如果node为null,说明是叶子节点,直接返回true
        if (node == null) {
            return true;
        }
        // 如果当前节点的值不在上下边界范围内,返回false
        if (node.val <= low || node.val >= high) {
            return false;
        }

        // 递归判断当前节点的左右节点是否在相应的上线边界范围内
        return isValidBST(node.left, low, node.val) && isValidBST(node.right, node.val, high);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(5);
        root.left = new TreeNode(1);
        root.right = new TreeNode(4);
        root.right.left = new TreeNode(3);
        root.right.right = new TreeNode(6);

        System.out.println(isValidBST(root));
    }
}
[Daily Message] Life is not used to find answers, not to solve problems, but to live happily. Instead of going to work with a sad face, it is better to work for entertainment. Long live those who work hard!

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!