Leetcode 98 이진 검색 트리 문제 해결 방안을 확인하고 C ++에서 구현

문제 해결 아이디어 :

최대 값은 왼쪽 서브 트리의 루트 레벨보다 작은 동안 왼쪽과 오른쪽 서브 트리의 루트의 각, 이진 트리인지 확인> 발은 최소 값이 오른쪽 하위 트리의 루트 레벨> 발보다 더 크다.

왼쪽과 오른쪽 하위 트리에서 왼쪽 서브 트리의 루트를 모색하고있다, 당신은 최소를 얻을 수, 탐구 할 수있는 권리를 가지고, 당신은 최대 값을 얻을 수 있습니다.

 

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