方案1、中序遍历+数组递增
void InOrder(BiTree T)
{
if(T!=NULL)
{
InOrder(T->lchild);
cout<<T->data<<" ";
InOrder(T->rchild);
}
}
void SqInOrder(BiTree T)
{
stack<BiTree> s;
BiTree p=T;
while(p || !s.empty())
if(p)
{
s.push(p);
p=p->lchild;
}
else
{
p=s.top();
cout<<p->data<<" ";
s.pop();
p=p->rchild;
}
}
方案2、局部判断+遍历递增
bool isBST(TreeNode *root)
{
if(root == NULL)return true;
if (!isBST(root->left))return false;
if (!isBST(root->right))return false;
TreeNode *cur = root->left;
if (cur != NULL)
{
while(cur->right!=NULL)cur = cur->right;
if(root->key < cur->key)return false;
}
TreeNode *cur = root->right;
if (cur != NULL)
{
while(cur->left!=NULL)cur = cur->left;
if(root->key > cur->key)return false;
}
return true;
}
方案3、局部判断的同时前后判断
bool isBST(TreeNode *root)
{
static TreeNode *prev;
if(root != NULL)
{
if(!isBST(root->left))
return false;
if(prev != NULL && root->data < prev->data)
return false;
prev = root;
if(!isBST(root->right))
return false;
}
return true;
}
方案4、中序 镜像遍历 Morris Traversal(最优)
void inorderMorrisTraversal(TreeNode *root) {
TreeNode *cur = root, *prev = NULL;
while (cur != NULL)
{
if (cur->left == NULL)
{
printf("%d ", cur->val);
cur = cur->right;
}
else
{
prev = cur->left;
while (prev->right != NULL && prev->right != cur)
prev = prev->right;
if (prev->right == NULL)
{
prev->right = cur;
cur = cur->left;
}
else
{
prev->right = NULL;
printf("%d ", cur->val);
cur = cur->right;
}
}
}
}