当前位置: 首页 > 文档资料 > LeetCode 题解 >

Tree - Validate Binary Search Tree

优质
小牛编辑
134浏览
2023-12-01

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.

这题需要判断是不是一个正确的二叉搜索树,比较简单地一道题。

我们通过递归整棵树来解决,代码如下:

  1. class Solution {
  2. public:
  3. bool isValidBST(TreeNode *root) {
  4. return valid(root, numeric_limits<int>::min(), numeric_limits<int>::max());
  5. }
  6. bool valid(TreeNode* node, int minVal, int maxVal) {
  7. if(!node) {
  8. return true;
  9. }
  10. if(node->val <= minVal || node->val >= maxVal) {
  11. return false;
  12. }
  13. return valid(node->left, minVal, node->val) &&
  14. valid(node->right, node->val, maxVal);
  15. }
  16. };