Leetcode题目98.验证二叉搜索树(递归-中等)

题目描述:

给定一个二叉树,判断其是否是一个有效的二叉搜索树。

假设一个二叉搜索树具有如下特征:

节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。

示例 1:

输入:
    2
   / \
  1   3
输出: true
示例 2:

输入:
    5
   / \
  1   4
     / \
    3   6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
     根节点的值为 5 ,但是其右子节点值为 4 。

思路分析:递归

因为二叉搜索树中序遍历是递增的,所以我们可以中序遍历判断前一数是否小于后一个数.

代码实现:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    TreeNode preNode=null;
    public boolean isValidBST(TreeNode root) {
        
                if (root == null) {
            return true;
        }
        if (!isValidBST(root.left)) {
            return false;
        }
        if (preNode != null && preNode.val >= root.val) {
            return false;
        }
        preNode = root;
        return isValidBST(root.right);
        
    }
}
  • 时间复杂度 : O(N)。每个结点访问一次。
  • 空间复杂度 : O(N)。我们跟进了整棵树。
posted @ 2019-11-08 16:18  菜鸟奋斗史  阅读(186)  评论(0编辑  收藏  举报