简体   繁体   中英

To find if a tree is a binary search tree or not

Is this method wrong for finding out if the tree is a BST or not? 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.And Both the left and right subtrees must also be binary search trees. My code is:

isBST(struct node* node) 
{ 
  if (node == NULL) 
    return 1; 
  if (node->left != NULL && node->left->data > node->data) 
    return 0; 
  if (node->right != NULL && node->right->data < node->data) 
    return 0; 
  if (!isBST(node->left) || !isBST(node->right)) 
    return 0; 
  return 1; 
}

No this method is wrong because it would return a true answer for this tree:

     6
    / \
   4   9
  / \
 2   10

Although it is not a binary search tree! I would suggest a better approach would be to take the inorder traversal and verify if it is actually sorted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM