Leetcode 98. 验证二叉搜索树 解题思路及C++实现

解题思路:

分别验证root的左右子树是否是二叉树,同时,左子树的最大值要小于root->val,右子树的最小值要大于root->val。

在左右子树中,一直向root的左子树探索,就能得到其最小值,一直向右探索,就能得到其最大值。

/**
 * 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;
    }
};

猜你喜欢

转载自blog.csdn.net/gjh13/article/details/92109267
今日推荐