您的位置:首页 > 其它

LeetCode 98: Validate Binary Search Tree

2013-09-03 15:49 471 查看
Difficulty: 3

Frequency: 5

Problem:

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.
Solution:

/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int i_biggest, i_smallest;
return isValidBSTRecursive(root, i_biggest, i_smallest);
}
bool isValidBSTRecursive(TreeNode * root, int & i_biggest, int & i_smallest)
{
if (root==NULL)
return true;
int i_biggest_left, i_smallest_left;
int i_biggest_right, i_smallest_right;
if (root->left==NULL)
{
i_smallest = root->val;
}
else
{
if (!isValidBSTRecursive(root->left, i_biggest_left, i_smallest_left))
return false;

if (i_biggest_left>=root->val)
return false;

i_smallest = i_smallest_left;
}

if (root->right==NULL)
{
i_biggest = root->val;
}
else
{
if (!isValidBSTRecursive(root->right, i_biggest_right, i_smallest_right))
return false;

if (i_smallest_right<=root->val)
return false;

i_biggest = i_biggest_right;
}
return true;
}
};

Notes:

Someone use DFS? I will try it later.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: