Leetcode 98. Validate Binary Search Tree

 

 

用一个right记录正确与否,long int保存最小值,进行一轮中序遍历,每次比较pre和当前值,如果小于当前值,更新pre,否则,将right置为错误即可

/**
 * 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 right = true;
    long int pre = -9999999999;
    bool isValidBST(TreeNode* root) {
        inOrder(root);
        return right;
    }
    void inOrder(TreeNode* root) {
        if(!root) return;
        inOrder(root->left);
        if(pre < root->val) pre = root->val;
        else right = false;
        inOrder(root->right);
    }
};

 

posted @ 2020-02-08 09:51  SteveYu  阅读(175)  评论(0编辑  收藏  举报