leetcode [98]Validate Binary Search Tree

Posted 小白兔云

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode [98]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.

Example 1:

Input:
    2
   /   1   3
Output: true

Example 2:

    5
   /   1   4
     /     3   6
Output: false
Explanation: The input is: [5,1,4,null,null,3,6]. The root node‘s value
             is 5 but its right child‘s value is 4.

题目大意:

查看这个树是否满足二叉搜索树的要求。

解法:

如果满足二叉搜索树,那么这个树的中序遍历一定是升序的,所以利用中序遍历查看序列是否是满足升序条件即可。

java:

class Solution {
    public boolean isValidBST(TreeNode root) {
        Stack<TreeNode>s=new Stack<TreeNode>();
        TreeNode pre=null;
        while(!s.empty()||root!=null){
            while(root!=null){
                s.push(root);
                root=root.left;
            }
            root=s.pop();
            if(pre!=null && pre.val >= root.val) return false;
            pre=root;
            root=root.right;
        }
        return true;
    }
}

还有一种解法,就是递归的判断左右子树是否在给定数值范围内。

java:

class Solution {
    public boolean isVaildBSTCore(TreeNode root,long minVal,long maxVal){
        if(root==null) return true;
        if(minVal>=root.val || maxVal<=root.val) return false;
        return isVaildBSTCore(root.left,minVal,root.val)&&isVaildBSTCore(root.right,root.val,maxVal);
    }

    public boolean isValidBST(TreeNode root) {
        if(root==null) return true;
        return isVaildBSTCore(root,Long.MIN_VALUE,Long.MAX_VALUE);
    }
}

  

以上是关于leetcode [98]Validate Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 98. Validate Binary Search Tree

leetcode 98 - Validate Binary Search Tree

Leetcode 98. Validate Binary Search Tree

leetcode [98]Validate Binary Search Tree

LeetCode 98. Validate Binary Search Tree

[LeetCode_98]Validate Binary Search Tree