一. 題目描述
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.confused what “{1,#,2,3}” means?
二. 題目分析
這道題的大意是,判斷一個二叉查找樹是否合法的,這個可以根據二叉查找樹的定義來進行判斷,即一個內部結點的值要大於左子樹的最大值,同時要小於右子樹的最大值。
根據這個定義,可以遞歸得進行判斷,這種方法得時間復雜度為O(n)
,空間復雜度為O(logn)
。這道題要注意的地方就是要記得更新以結點為父節點的樹的最大值和最小值,以便遞歸返回時給上一個調用進行判斷。
三. 示例代碼
#include
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution
{
private:
bool isValidBST(TreeNode* root, int &MinValue, int &MaxValue)
{
if (!root)
{
return true;
}
if (root->left)
{
if (root->val <= root->left->val)
{
return false;
}
int LeftMinValue = 0;
int LeftMaxValue = 0;
if (!isValidBST(root->left, LeftMinValue, LeftMaxValue))
{
return false;
}
else
{
MinValue = LeftMinValue;
if (LeftMaxValue != LeftMinValue)
{
if (root->val <= LeftMaxValue)
{
return false;
}
}
}
}
else
{
MinValue = root->val;
}
if (root->right)
{
if (root->val >= root->right->val)
{
return false;
}
int RightMinValue = 0;
int RightMaxValue = 0;
if (!isValidBST(root->right, RightMinValue, RightMaxValue))
{
return false;
}
else
{
MaxValue = RightMaxValue;
if (RightMaxValue != RightMinValue)
{
if (root->val >= RightMinValue)
{
return false;
}
}
}
}
else
{
MaxValue = root->val;
}
return true;
}
public:
bool isValidBST(TreeNode* root)
{
int MinValue = 0;
int MaxValue = 0;
bool IsLeaf = true;
return isValidBST(root, MinValue, MaxValue);
}
};