LeetCode | Validate Binary Search Tree

题目:

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.

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

思路:

方法1:递归调用,每次递归的时候需要将取值范围传递进下一层 方法2:前序遍历

代码:

方法1:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {  
public:  
    bool isValidBST(TreeNode *root) {  
        return isValidNode(root, INT_MAX, INT_MIN); 
    }  
      
    bool isValidNode(TreeNode * p, int max, int min)  
    {  
        if(p == NULL)  
        {  
            return true;  
        }
        else if((p->val == INT_MIN && p->left != NULL) || (p->val == INT_MAX && p->right != NULL)) 
        {  
            return false;  
        }  
        else if(p->val <= max && p->val >= min)  
        {  
            return isValidNode(p->left, p->val - 1, min) && isValidNode(p->right, max, p->val + 1);  
        }  
        else  
        {  
            return false;  
        }  
    }  
};  

方法2:

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode * pre;
    TreeNode * cur;
    bool isValidBST(TreeNode *root) {
        if(root == NULL){
            return true;
        }
        
        pre = NULL;
        cur = NULL;
        return goTree(root);
    }
    
    bool goTree(TreeNode *root) {
        if(root == NULL){
            return true;
        }
        bool b1 = goTree(root->left);
        pre = cur;
        cur = root;
        if(pre != NULL && cur->val <= pre->val){
            return false;
        }
        bool b2 = goTree(root->right);
        return b1 && b2;
    }
};
    原文作者:Allanxl
    原文地址: https://blog.csdn.net/lanxu_yy/article/details/11819759
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞