[geekforgeeks] Check if a binary tree is BST or not

题目链接:http://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/

A binary search tree (BST) is a node based binary tree data structure which has the following properties.
• 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.

From the above properties it naturally follows that:
• Each node (item in the tree) has a distinct key.

[geekforgeeks] Check if a binary tree is BST or not_第1张图片



思路: 判断一个树是不是不是二叉搜索树不能简单的判断左子树值比根节点小, 右子树值比根节点大, 因为还可能存在这种情况:

[geekforgeeks] Check if a binary tree is BST or not_第2张图片所以我们可以在搜索一个结点的时候附带上其允许的值范围, 并且每次递归搜索左子树的时候其最大值将会是根结点. 搜索右子树的时候其最小值将会是根节点.

代码如下:

int isBST(struct node* node) 
{ 
    if (node == NULL) 
	    return 1; 
	return isBST(node, INT_MIN, INT_MAX);
}

bool isBST(struct node* node, int min, int max)
{
    if(node==NULL) return true;
    if(node->data < min || node->data > max)
        return false;
    return isBST(node->left, min, node->data-1) 
           && isBST(node->right, node->data+1, max);
}



你可能感兴趣的:(tree,binary,geeksforgeeks)