leetcode 98. 验证二叉搜索树

给定一个二叉树,判断其是否是一个有效的二叉搜索树。

一个二叉搜索树有如下定义:

  • 左子树只包含小于当前节点的数。
  • 右子树只包含大于当前节点的数。
  • 所有子树自身必须也是二叉搜索树。

示例 1:

    2
   / \
  1   3

二叉树[2,1,3], 返回 true.

示例 2:

    1
   / \
  2   3

二叉树 [1,2,3], 返回 false.


啊我有点蠢了。。中序遍历做

/**
 * 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) {
            long long f = -0x3f3f3f3f3f3f;
            return dfs(root, f);
        }
        else
            return true;
    }
    
    bool dfs(TreeNode* root, long long& f_val) {
        bool res = true;
        if (root) {
            res &= dfs(root->left, f_val) && (root->val > f_val);
            if (!res)
                return false;
            f_val = root->val;
            res &= dfs(root->right, f_val);
        }
        return res;
    }
};

你可能感兴趣的:(leetcode)