leetcode - 98. Validate Binary Search Tree

树的中序遍历
在这里插入图片描述

/**
 * 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 visit(TreeNode* p,int& pre,bool& f)
    {
        if(p->left)
        {
            if(!visit(p->left,pre,f)) return 0;
        }
        if(f)
        {
            if(p->val<=pre) return 0;
        }else{
            f=1;
        }
        pre=p->val;
        if(p->right)
        {
            if(!visit(p->right,pre,f)) return 0;
        }
        return 1;
        
    }
    bool isValidBST(TreeNode* root) {
        if(!root) return 1;
        bool f(0);
        int pre(INT_MIN);
        return visit(root ,pre,f);
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41938758/article/details/89005724