【一天一道LeetCode】#98. Validate Binary Search Tree

时间:2023-03-08 21:28:26
【一天一道LeetCode】#98. Validate Binary Search Tree

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处

(一)题目

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:

  2

  / \

 1 3

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

Example 2:

  1

  / \

 2 3

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

(二)解题

题目大意:给定一个二叉树,判断该树是不是二叉搜索树。

解题思路:二叉搜索树满足,对于一个父节点,左子树所有节点的数值小于父节点的数值,右子树的所有节点的数值大于父节点的数值。

我的做法是采用递归的方法,并用一对min和max来记录左/右子树需要满足的数值范围。对于一个父节点root,需要满足在(min,max)范围内,然后判断左右节点,需要满足left

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isValidBST(TreeNode* root) {
        if(root==NULL) return true;
        return dfsValidBST(root,-2147483649,2147483648);//这里初始范围设为INT_MIN-1,INT_MAX+1
    }
    bool dfsValidBST(TreeNode* root , long min , long max)
    {
        if(root->val<=min||root->val>=max) return false;
        bool left = true;
        bool right = true;
        if(root->left!=NULL)//left不为空
        {
            if(root->left->val < root->val) left = dfsValidBST(root->left,min,root->val);//满足条件继续往左子树搜索,min和max更新
            else left = false;
        }
        if(root->right!=NULL)//right不为空
        {
            if(root->right->val > root->val) right = dfsValidBST(root->right,root->val,max);//满足条件继续往右子树搜索,min和max更新
            else right = false;
        }
        return left&&right;//二者都为true,才返回true
    }
};