一道很经典的算法题,也应该是所有计算机专业学生在初学数据结构时做过的问题,尽管如此,我还是想把它写下来,这道问题就是判断一棵二叉树是否为二叉搜索树(BST)?
在LeetCode上我写了两种解法,一种就是按照定义递归的把条件写出来再判断(直接法),另一种就是利用BST的性质:中序遍历结果为升序(性质法),注意空树是符合BST定义的。
首先是直接法,其实就是定义的代码翻译:
(1)节点的左子树只包含小于当前节点的数。
(2)节点的右子树只包含大于当前节点的数。
(3)所有左子树和右子树自身必须也是二叉搜索树。
代码如下:
// 下面1,2两个函数来判断左右子树是否BST的条件(1)(2)
// (1)determine whether the left child tree satisfys the BST condition
bool isLeftLittle(TreeNode* Left, int Value)
{
if(Left == nullptr)
return true;
if(Left->val >= Value)
return false;
return isLeftLittle(Left->left, Value) && isLeftLittle(Left->right, Value);
}
// (2)determine whether the right child tree satisfys the BST condition
bool isRightLarger(TreeNode* Right, int Value)
{
if(Right == nullptr)
return true;
if(Right->val <= Value)
return false;
return isRightLarger(Right->left, Value) && isRightLarger(Right->right, Value);
}
// 主函数
bool isValidBST(TreeNode* root) {
if(root == nullptr)
return true;
// 分别判断左右子树是否分别小于和大于根节点的值
if((isLeftLittle(root->left, root->val) && isRightLarger(root->right, root->val)) == 0)
return false;
// 再判断左右子树是否分别为BST
return isValidBST(root->left) && isValidBST(root->right);
}
其次是性质法,这个方法对此问题来说是最好的:
// 中序遍历,结果存入Result向量中
void inOrder(TreeNode* Root, vector<int>& Result)
{
if(Root == nullptr)
return;
inOrder(Root->left, Result);
Result.push_back(Root->val);
inOrder(Root->right, Result);
}
// 判断是否为升序序列
bool isAscendOrder(vector<int> Result)
{
for(auto i = 0 ; i < Result.size() - 1 ; ++i)
if(Result[i] >= Result[i + 1])
return false;
return true;
}
// 主函数
bool isValidBST(TreeNode* root) {
if(root == nullptr)
return true;
vector<int> Result;
inOrder(root, Result);
return isAscendOrder(Result);
}