Leetcode 98. Validate Binary Search Tree 判断是不是搜索二叉树

解决思路:递归

Leetcode 98. Validate Binary Search Tree 判断是不是搜索二叉树

在bool isValidBST(TreeNode* root, TreeNode* min, TreeNode* max)函数中,min和max节点限定了root的取值范围,如果root节点的值不满足 (min,max),则返回false,在递归的过程中,不断更新 (min,max),来判断根节点和子节点是否满足关系。

class Solution {
public:
    bool isValidBST(TreeNode* root) {
        return isValidBST(root, nullptr, nullptr);
    }
    bool isValidBST(TreeNode* root, TreeNode* min, TreeNode* max)
    {
        if(root == nullptr)
            return true;
        if((min && min->val >= root->val) || (max && max->val <= root->val))
            return false;
                //把左子树的的最大值限定为root的值        //把右子树的的最小值限定为root的值
        return isValidBST(root->left, min, root) && isValidBST(root->right, root, max);
    }
};

 

相关文章:

  • 2022-02-05
  • 2022-01-25
  • 2021-08-23
  • 2021-03-30
  • 2021-10-24
  • 2022-01-01
  • 2021-08-02
  • 2021-06-27
猜你喜欢
  • 2022-01-11
  • 2022-02-19
  • 2021-09-12
  • 2021-07-24
  • 2022-12-23
  • 2022-12-23
  • 2021-06-17
相关资源
相似解决方案