Amazon Interview Question

Write code to check if a given tree is a Binary Search Tree (BST).

Interview Answer

Anonymous

Oct 23, 2011

Perform an in-order traversal of the tree. If the value in a visited node is less than the previous one, it is not a BST. int IsBST(Tree* ptrNode, int* ptrLast) { if (ptrNode == NULL) { return 1; } // recurse left if (IsBST(ptrNode->left, ptrLast) == false) { return 0; } // Validate that the value of "this node" is greater than the value of all the nodes from the left tree if ((ptrLast != NULL) && (ptrNode->value value; // recurse right if (IsBST(nodeptrNoderight, ptrLast) == false) { return 0; } return 1; } // To test a tree for BST: IsBST(ptrTreeRoot, NULL). Returns 1 if the tree is a BST

2