Exercise 4.3 Is a Binary Search Tree (25 points)

First introduce the first method, followed by traversal.

The idea is very simple, each recursive call to the judgment function can bring back the maximum and minimum values ​​of the subtree T. In addition, pay attention to one point in the definition of binary search tree. Simply put, the value of the root node must be greater than the maximum value of the left subtree and less than the minimum value of the right subtree . Never just judge the relationship between the root node and the size of the left and right children.

/*后序遍历判断*/
bool preJudge(BinTree T, int *minT, int *maxT)
{
    int lmin,lmax,rmin,rmax;
    bool ans1 = false, ans2 = false;
    if(T==NULL) return true;//递归基
    if((T->Left&&preJudge(T->Left,&lmin,&lmax)&&T->Data>lmax)||!T->Left)
        ans1 = true;//左子树为空,左子树为BST;左子树不为空则判断左子树是否为BST,再判断根结点是否大于左子树的最大值
    if((T->Right&&preJudge(T->Right,&rmin,&rmax)&&T->Data<rmin)||!T->Right)
        ans2 = true;//同上
    if(ans1&&ans2)
    {
        if(T->Left == NULL) *minT = T->Data;//左子树为空,那么T的最小值为T->Data;
        else *minT = lmin;
        if(T->Right == NULL) *maxT = T->Data;//同上
        else *maxT = rmax;
        return true;
    }
    else return false;
}
bool IsBST(BinTree T)//统一接口
{
    int minT,maxT;
    return preJudge(T,&minT,&maxT);
}

 

Method 1 actually requires 25 lines of code to solve a 25-point problem, is it too much trouble...

So we have a method with fewer codewords . The sequence of the middle order traversal of the binary search tree is non-decreasing . Using this property, we can run the preorder traversal once and set a global variable pre to judge whether the sequence is monotonous.

/*中序遍历判断*/
int pre = -1;
bool IsBST(BinTree T)
{
	if(!T) return true;
	IsBST(T->Left);
	if(T->Data < pre) return false;
	else pre = T->Data;
	IsBST(T->Right);
	return true;
}	

Unexpectedly, 10 lines of code will do...

Guess you like

Origin blog.csdn.net/yiwaite/article/details/101035420