binary-search-treeinorder

Inorder traversal to verify that binary tree is a BST


I am currently working on a Binary Search Tree project, and I would like to implement an inorder traversal:

void inorder(struct node *root)
{
    if(root!=NULL) // checking if the root is not null
    {
        inorder(root->left_child); // visiting left child
        printf(" %d ", root->data); // printing data at root
        inorder(root->right_child);// visiting right child
    }
}

However, my BST varies between 100000 and 1000000 keys, and as you can imagine, printing them all is not very "handy". Can this inorder function be modified so it only prints "The binary tree is a BST"? I have been trying to implement it but I really can't find a solution.


Solution

  • It looks like you want to verify whether a tree is actually a valid BST, i.e. its in-order traversal would visit its values in non-decreasing order.

    For that you need a different function. Here is how it could be done:

    int isValidBstHelper(struct node *root, int low, int high) {
        return root == NULL || 
            (root->data >= low && root->data <= high &&
             isValidBstHelper(root->left_child, low, root->data) &&
             isValidBstHelper(root->right_child, root->data, high)); 
    }
    
    int isValidBst(struct node *root) {
        return isValidBstHelper(root, INT_MIN, INT_MAX);
    }
    

    isValidBst will return 1 when the tree is a valid BST and 0 when it is not.

    To print the result, just call like this:

    if (isValidBst(root)) {
        printf("The tree is a valid BST");
    } else {
        printf("The tree is NOT a valid BST");
    }