二叉樹中序遍歷的情況下,遍歷結果是所有節點依次升序的,就是搜索二叉樹,否則就不是。
由此我們可以對之前非遞歸版本的中序遍歷稍加修改,在打印節點的時機判斷當前節點是否大於上一個節點,就可以判斷此二叉樹是否是搜索二叉樹。
思路:
1中序遞歸遍歷二叉樹,將結果保存進一個stack
2比較大小,棧頂爲大,棧頂爲小。
測試代碼
#include<iostream>
#include<stdlib.h>
#include<stack>
#include<queue>
using namespace std;
#define len 15 //定義一個長度
typedef int ElemType;
typedef struct BiTNode
{
ElemType data;
struct BiTNode *lchild, *rchild;
}BiTNode, *BiTree;
typedef struct Node
{
BiTree btnode;
bool isfirst;
}Node,*node;
//向下遍歷,找到節點s應該插入的位置,節點有重複時,忽略這個節點
void SearchTreeNode(BiTree &root, BiTree &s) //注意:使用引用傳遞
{
if (root == NULL)
return;
if (s->data > root->data)
{
if (root->rchild == NULL)
{
root->rchild = s;
return;
}
SearchTreeNode(root->rchild, s);//s值大於根節點值,未到達葉子節點,繼續向右孩子遍歷
}
else if (s->data < root->data)
{
if (root->lchild == NULL)
{
root->lchild = s;
return;
}
SearchTreeNode(root->lchild, s);//s值小於根節點值,未到達葉子節點,繼續向左孩子遍歷
}
}
//插入一個節點,樹爲空,插入節點即爲根節點,否則找合適的位置插入
void InsertNode(BiTree &tree, BiTree &s) //注意:使用引用傳遞
{
if (tree == NULL)
tree = s;
else
SearchTreeNode(tree, s);
}
//二叉排序樹創建,每次增加一個結點,插到現有的二叉樹上去
void CreateOrderBinaryTree(BiTree &tree, int *a)
{
for (int i = 0; i < len; i++)
{
BiTree s = (BiTree)malloc(sizeof(BiTNode));
s->data = a[i];
s->lchild = NULL;
s->rchild = NULL;
InsertNode(tree, s);
}
}
//判斷是否爲搜索二叉樹,藉助中序遍歷
void midOrder(BiTree pRoot,stack<BiTree>& help){
if(!pRoot)
return;
midOrder(pRoot->lchild, help);
help.push(pRoot);
midOrder(pRoot->rchild, help);
}
bool isSearchTree(BiTree pRoot)
{
stack<BiTree> help;
midOrder(pRoot, help);
int Min = INT_MAX;
while (!help.empty()) {
pRoot = help.top();
help.pop();
if (Min < pRoot->data)return false;
else {
Min = pRoot->data;
}
}
return true;
}
int main()
{
int a[len] = { 62, 88, 58, 47, 35, 73, 51, 99, 37, 93, 23, 27, 45, 21, 12 };
BiTree tree = NULL;
//創建一個二叉樹,並中序遍歷
CreateOrderBinaryTree(tree, a);
cout<<endl;
cout << "判斷是否是搜索二叉樹" << endl;
if(isSearchTree(tree)) cout<<"是搜索二叉樹"<<endl;
else cout<<"不是搜索二叉樹"<<endl;
return 0;
}
測試結果
代碼參考:https://blog.csdn.net/weixin_41767070/article/details/94005830