• LeetCode 98. Validate Binary Search Tree


    原题链接在这里:https://leetcode.com/problems/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:

    • 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. 

    题解:

    根据BST特性递归调用原函数,如果出现root.val >= max 或者root.val <= min的情况return false. 

    Note: 初始的max 和 min 要设成long 型的最大最小值,因为边界的corner case. 若是用Integer.MAX_VALUE. 并且数只有一个节点,刚开始若root.val = Integer.MAX_VALUE, 会返回false. 其实应该返回true.

    Time Complexity: O(n). Space: O(logn).

    AC Java:

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

    另外一种方法是做inorder traverse, 若是出现逆序,就返回false.

    Time Complexity: O(n). Space: O(logn).

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     TreeNode prev;
    12     public boolean isValidBST(TreeNode root) {
    13         if(root == null){
    14             return true;
    15         }
    16         //左边
    17         if(!isValidBST(root.left)){
    18             return false;
    19         }
    20         //中间
    21         if(prev != null && prev.val >= root.val){
    22             return false;
    23         }
    24         prev = root;
    25         //右边
    26         if(!isValidBST(root.right)){
    27             return false;
    28         }
    29         return true;
    30     }
    31 }
  • 相关阅读:
    报错18:28:21: Debugging starts QLayout: Attempting to add QLayout ““ to MainWindow “MainWindow“, which
    春 景
    sysTime(系统毫秒)
    balabala视频格式转换器
    tasklist /FI命令结论
    QFileSystemWatcher
    Qfileinfo
    Qdir
    欢迎光临我的普吉岛芭东海滩公寓
    使用ArcGIS GP服务之一框架介绍
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824973.html
Copyright © 2020-2023  润新知