validate a binary tree is BST
思路: bst的中序遍历序列是严格递增的。
1. 空树是BST
2. 左子树是BST && 右子树是BST
3. 左子树 && 根 && 右子树 能构成BST.
sample code
/* 判定二叉树是否是BST
* 第二参数的意义:前一个被访问节点的值,需要使用引用
* 时间复杂度O(n),需要逐个遍历树中的元素。
* 思路: bst的中序序列是严格递增的
*/
bool is_bst_by_in(node *root, int& preval)
{
if (!root) return true; /* 很重要 */
if (is_bst_by_in(root->l, preval))
{
if (root->dat > preval) /* 合法情况 */
{
preval = root->dat;
return is_bst_by_in(root->r, preval);
}
else
{
return false;
}
}
else
{
return false;
}
}
bool isBst(node *root)
{
int pre = INT_MIN;
return is_bst(root, pre);
}
determine whether a binary search tree pre-order traversal sequence is valid
for a pre-ordered binary search tree traversal sequence, to determine whether it is valid is somewhat difficult in a linear time complexity.
you need to check each sub trees in root left right order. A stack can help solve the problem.