leetcode98 - Validate Binary Search Tree - medium

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.

 

对于每个node,都有一个限制的range,以此进行递归。node为null是返回的是true

注意的是这里取INT_LIMITS会out of range, 用long就好

 

实现:O(n), 访问每个node exactly once

 1 class Solution {
 2 public:
 3     bool isValidBST(TreeNode* root) {
 4         return helper(root, LONG_MIN, LONG_MAX);
 5     }
 6     
 7     bool helper(TreeNode* root, long min, long max){
 8         if (!root) return true;
 9         if (root->val <= min || root->val >= max) return false;
10         return helper(root->left, min, root->val) && helper(root->right, root->val, max);
11     }
12 };

 

posted @ 2020-08-04 09:40  little_veggie  阅读(85)  评论(0)    收藏  举报