1.测试用例没有考虑INT_MIN,以至于一开始采用INT_MIN作为最小值。
Solution:采用is_first变量,以存储第一个值;
2.单独用递归程序写时,容易导致很多错误,并不能真正验证是否是一个合格的二叉排序树。比如,右子树中的某个节点大小有可能小于该节点的值,这样的二叉树就不是二杈排序树。错误代码如下:
//bool isValidBST(TreeNode *root)
//{
// if(!root)
// return true;
// if(!root->left && !root->right)
// return true;
// if(root->left && root->right)
// {
// if(root->left->val>=root->val || root->right->val<=root->val)
// return false;
// return isValidBST(root->left) && isValidBST(root->right);
// }
// if(root->left && !root->right)
// {
// if(root->left->val>=root->val)
// return false;
// return isValidBST(root->left);
// }
// if(!root->left && root->right)
// {
// if(root->right->val<=root->val)
// return false;
// return isValidBST(root->right);
// }
3.二叉排序树的遍历应该采用中序遍历,遍历的结果一定是从小到大的,否则就不是valid binary sorting tree.
4.在采用中序遍历时,采用的数据结构是栈,注意判断循环结束的条件是当前节点的左右子树为空,且栈为空。
// 正确的解法:采用中序遍历
bool isValidBST(TreeNode *root)
{
if(!root || !root->left&&!root->right)
return true;
int pre;
int cur;
bool is_head = true;
TreeNode *temp = root;
stack<TreeNode *> st;
while(temp)
{
while(temp->left)
{
st.push(temp); //节点暂时保存在栈中
temp = temp->left;
}
if(is_head)
{
pre = temp->val;
is_head = false;
}
else
{
cur = temp->val; // 找到左子树中无左孩子的节点(A)
if(cur <= pre) // 必须满足升序要求
return false;
pre = cur;
}
temp = temp->right; //去遍历A节点的右子树
if(temp) //如果A节点的右孩子不为空,则继续按照上面的步骤,寻找A节点
continue;
if(!temp&&st.empty())
break;
// 出栈,访问这些节点(中序便利的规则)
while(!st.empty())
{
temp = st.top();
st.pop();
cur = temp->val;
if(cur <= pre)
return false;
pre = cur;
if(temp->right)
break;
}
temp = temp->right;
}
return true;
}