码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode 98 - Validate Binary Search Tree

时间:2019-08-20 01:06:24      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:fine   treenode   ==   btree   ret   sum   ova   span   tco   

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

标签:fine   treenode   ==   btree   ret   sum   ova   span   tco   

原文地址:https://www.cnblogs.com/SHQHDMR/p/11380563.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!