Leetcode—98. Validate Binary Search Tree

Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

The left subtree of a node contains only nodes with keys less than the node's key.

The right subtree of a node contains only nodes with keys greater than the node's key.

Both the left and right subtrees must also be binary search trees.


合法查找二叉树的检验。

要求所有左节点值比自身小,所有右节点值比自身大。

因此在每次返回的函数中,节点N的左节点应大于N应该大于的值&&小于N,右节点应大于N&&小于N应该小于的值。



/**

* Definition for a binary tree node.

扫描二维码关注公众号,回复: 6433902 查看本文章

* 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 isValidBST(root, NULL, NULL);

    }

    bool isValidBST(TreeNode* root, TreeNode* minNode, TreeNode* maxNode) {

        if(!root) return true;

        if(minNode && root->val <= minNode->val || maxNode && root->val >= maxNode->val)

            return false;

        return isValidBST(root->left, minNode, root) && isValidBST(root->right, root, maxNode);

    }

};

猜你喜欢

转载自blog.csdn.net/weixin_34290000/article/details/90991338