098 Validate Binary Search Tree [Leetcode]

来源:互联网 发布:桌面整理软件推荐 编辑:程序博客网 时间:2024/06/05 04:10

题目内容:

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.

分析:
可做的方法有两种:
1. 对二叉树进行中序排序,如果排序结果是递增的说明正确,否则错误。这里比起排序后比较有一个更快的办法,即直接比较上一个读取的数,因为中序遍历总是按序读取的。
2. 记录最大值和最小值。这相当于模拟了二叉搜索树的生成过程。给定一个节点,它左子树的节点范围的最大值不会超过当前节点。同样,右子树中的最小值也不会低于当前节点的值。这样递归判断。

方法一的代码:运行时间16ms,注意当最小值为INT_MIN时的处理。

/** * 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) {        int pre(INT_MIN);        bool change(false);        return isValid(root, pre, change);    }    bool isValid(TreeNode *node, int &pre, bool &change) {        if(node == NULL)            return true;        if(!isValid(node->left, pre, change))            return false;        if(node->val == INT_MIN && change)            return false;        if(node->val <= pre && pre != INT_MIN)            return false;        pre = node->val;        change = true;        if(!isValid(node->right, pre, change))            return false;        return true;    }};

方法二的代码:有一点非常恶心的地方是会出现节点值和最大值相同的情况,因此判断条件不能够简单得写成>=min或<=max,要考虑特殊情况。因此要记录当前的INT_MIN或INT_MAX是否是初始化的那个值还是重复出现。运行时间为16ms。

/** * 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 isValid(root, INT_MIN, INT_MAX, false, false);    }    bool isValid(TreeNode* root, int min, int max, bool change_min, bool change_max) {        if(root == NULL)            return true;        int value = root->val;        if(value == INT_MIN && root->left == NULL && !change_min) {            return isValid(root->right, value, max, true, change_max);        }        if(value == INT_MAX && root->right == NULL && !change_max) {            return isValid(root->left, min, value, change_min, true);        }        if(value >= max || value <= min) {            return false;        }        return isValid(root->left, min, value, change_min, true) && isValid(root->right, value, max, true, change_max);    }};
0 0