98. Validate Binary Search Tree

Description

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.

Example 1:

tree

Binary tree [2,1,3], return true.

Example 2:

tree

Binary tree [1,2,3], return false.

Solution

DFS, time O(n)

注意处理overflow!

eg: [-2147483648,-2147483648], return false.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        return isValidBST(root, Integer.MIN_VALUE, Integer.MAX_VALUE);
    }
    
    // take long as input to avoid overflow
    public boolean isValidBST(TreeNode root, long min, long max) {
        if (root == null) {
            return true;
        }
        
        if (root.val < min || root.val > max) {
            return false;
        }
        
        return isValidBST(root.left, min, root.val - 1l)    // convert to long
            && isValidBST(root.right, root.val + 1l, max);
    }
}

Inorder-traversal, time O(n), space O(n)

BST的inorder traversal是有序的!要谨记这个特性。用Stack来实现inorder traversal。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public boolean isValidBST(TreeNode root) {
        // inorder traversal
        TreeNode pre = null;
        TreeNode curr = root;
        Stack<TreeNode> stack = new Stack<>();
        
        while (curr != null || !stack.empty()) {
            while (curr != null) {  // push all left nodes
                stack.push(curr);
                curr = curr.left;
            }
            
            curr = stack.pop();
            if (pre != null && curr.val <= pre.val) {
                return false;
            }
            
            pre = curr;
            curr = curr.right;
        }
        
        return true;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容