leetcode 98 - Validate Binary Search Tree

Posted shqhdmr

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

 

时间空间均超70%的方法,写的有点复杂:

思路是,当前节点左右都满足BST的条件下,还要顺便找出左子树的最大值leftMax和右子树的最小值rightMin,以防leftMax大于root->val或rightMin 小于 root->val

class Solution

public:
    bool isValidBST(TreeNode *root)
    
        int subLeftMax = INT_MIN, subLeftMin = INT_MAX, subRightMax = INT_MIN, subRightMin = INT_MAX;

        return this->doValid(root, &subLeftMax, &subLeftMin, &subRightMax, &subRightMin);
    

protected:
    bool doValid(TreeNode *root, int *leftMaxVal, int *leftMinVal, int *rightMaxVal, int *rightMinVal)
    
        bool result = true;

        int subLeftMax = INT_MIN, subLeftMin = INT_MAX, subRightMax = INT_MIN, subRightMin = INT_MAX;

        if (root == NULL || (root->left == NULL && root->right == NULL))
        
            return true;
        

        if ((root->left != NULL && root->left->val >= root->val) ||
            (root->right != NULL && root->right->val <= root->val))
        
            return false;
        

        result = this->doValid(root->left, &subLeftMax, &subLeftMin, &subRightMax, &subRightMin);

        if (result == false || (root->left != NULL && subLeftMax >= root->val)
            || (root->left != NULL && subRightMax >= root->val))
        
            return false;
        

        *leftMaxVal = max(max(subLeftMax, subRightMax), (root->left == NULL ? INT_MIN : root->left->val));
        *leftMinVal = min(min(subLeftMin, subRightMin), (root->left == NULL ? INT_MAX : root->left->val));

        subLeftMax = subRightMax = INT_MIN;
        subLeftMin = subRightMin = INT_MAX;

        result = this->doValid(root->right, &subLeftMax, &subLeftMin, &subRightMax, &subRightMin);

        if (result == false || (root->right != NULL && subLeftMin <= root->val)
            || (root->right != NULL &&subRightMin <= root->val))
        
            return false;
        

        *rightMaxVal = max(max(subLeftMax, subRightMax), (root->right == NULL ? INT_MIN : root->right->val));
        *rightMinVal = min(min(subLeftMin, subRightMin), (root->right == NULL ? INT_MAX : root->right->val));

        return  true;
    
;

 

以上是关于leetcode 98 - Validate Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 98. Validate Binary Search Tree

leetcode 98 - Validate Binary Search Tree

Leetcode 98. Validate Binary Search Tree

leetcode [98]Validate Binary Search Tree

LeetCode 98. Validate Binary Search Tree

[LeetCode_98]Validate Binary Search Tree