LeetCode 98. Validate Binary Search Tree

早过忘川 提交于 2020-02-26 16:25:17

原题链接在这里: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 }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!