leetcode-98-Validate Binary Search Tree

leetcode-98-Validate Binary Search Tree

98. Validate Binary Search Tree

Description Submission Solutions Add to List

  • Total Accepted: 141105
  • Total Submissions: 626297
  • Difficulty: Medium
  • Contributors: Admin

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.

Subscribe to see which companies asked this question.

(1), 使用递归解决。 

(2), 没想到测试用例这么极端, 居然就一定要到 int 的范围尽头, 记住 int 的范围 [-2147483648, 2147483647]

/**
 * 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 Judge(TreeNode* root, int leftval, int rightval){
        if(root == NULL){
            return true; 
        }
        if(root->val < leftval || root->val > rightval){
            return false; 
        }
        if(root->left && root->right){
            if(root->left->val < root->val && root->right->val > root->val){
                return Judge(root->left, leftval, root->val-1) && Judge(root->right, root->val+1, rightval); 
            }else{
                return false; 
            }
        }else if(root->left != NULL){
            if(root->left->val < root->val){
                return Judge(root->left, leftval, root->val-1); 
            }else{
                return false; 
            }
        }else if(root->right != NULL){
            if(root->right->val > root->val){
                return Judge(root->right, root->val+1, rightval); 
            }else{
                return false; 
            }
        }else{
            return true; 
        }
    }
    
    bool isValidBST(TreeNode* root) {
        return Judge(root, -2147483648, 2147483647); 
    }
};

  

原文地址:https://www.cnblogs.com/zhang-yd/p/6399172.html