(M)DFS:98. Validate Binary Search Tree

来源:互联网 发布:神经网络算法预测股市 编辑:程序博客网 时间:2024/05/17 06:15

这道题要想到每次代入最大值和最小值

/** * 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) {        return dfs(root, LONG_MIN, LONG_MAX);    }    bool dfs(TreeNode* root, long left, long right)    {        if(root == NULL) return true;        if(root->val <= left || root->val >= right) return false;        return dfs(root->left, left, root->val) && dfs(root->right, root->val, right);    }};