Leetcode 98. Verify binary search tree problem-solving ideas and implemented in C ++

Problem-solving ideas:

Verify whether each of the left and right subtree root is a binary tree, while the maximum value is smaller than the left subtree root-> val, the minimum value is greater than the right subtree root-> val.

In the left and right subtrees, has been exploring sub-tree root to the left, you can get its minimum, has the right to explore, you can get the maximum value.

 

/**
 * 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 isValidBST(TreeNode* root) {
        if(!root) return true;
        return isLeftBST(root->left, root->val) && isRightBST(root->right, root->val);
    }
    bool isLeftBST(TreeNode* root, int n){
        if(isValidBST(root)){
            while(root){
                if(root->val >= n) return false;
                root = root->right;
            }
            return true;
        }
        else return false;
    }
    bool isRightBST(TreeNode* root, int n){
        if(isValidBST(root)){
            while(root){
                if(root->val <= n) return false;
                root = root->left;
            }
            return true;
        }
        else return false;
    }
};

 

 

Guess you like

Origin blog.csdn.net/gjh13/article/details/92109267