zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    Python基础23_os,sys,序列化,pickle,json
    Python基础22_模块,collections,time,random,functools
    Python基础21_类与类型, MRO, C3算法, super()
    Python基础20_类的约束,异常处理,MD5加密,日志
    python反射机制
    python 依赖关系 与关联关系
    python 类的常见的特殊成员
    类的成员(*变量与*方法)
    初识面向对象
    简说匿名函数与递归
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/4824973.html
Copyright © 2011-2022 走看看