#include<stdio.h>
#include<stdlib.h>
#include <iostream>
using namespace std;
#define MAXSIZE 10
typedef struct node
{
char data;
struct node* lchild, * rchild;
}BSTree;
void Preorder(BSTree* p)
{
if (p != NULL)
{
cout << p->data;
Preorder(p->lchild);
Preorder(p->rchild);
}
}
BSTree* Search(BSTree* p, char x)//非递归中序遍历查找数据x
{
BSTree* stack[MAXSIZE];
int i = 0;
stack[0] = NULL;
while (i>=0)
{
if (p!=NULL)
{
if (p->data==x)
{
return p;
}
else
{
stack[++i] = p;
p = p->lchild;
}
}
else
{
p = stack[i--];
p = p->rchild;
}
if (p == NULL && i == 0)
break;
}
return NULL;
}
int Depth(BSTree* p)//后序遍历二叉树的深度
{
int lchild, rchild;
if (p==NULL)
{
return 0;
}
else
{
lchild = Depth(p->lchild);
rchild = Depth(p->rchild);
return lchild > rchild ? (lchild + 1) : (rchild + 1);
}
}
int CountLeaf(BSTree* p)//叶节点的数量
{
if (p == NULL)
return 0;
if (p->rchild == NULL && p->lchild == NULL)
return 1;
return(CountLeaf(p->lchild) + CountLeaf(p->rchild));
}
void Create(BSTree** p)
{
char ch;
scanf_s("%c", &ch);
if (ch!='.')
{
*p = (BSTree*)malloc(sizeof(BSTree));
(*p)->data = ch;
Create(&(*p)->lchild);
Create(&(*p)->rchild);
}
else
{
*p = NULL;
}
}
int main()
{
BSTree* root, * p;
char x;
printf("创建二叉树");
Create(&root);
printf("pre遍历");
Preorder(root);
cout << endl;
getchar();
printf("输入要查找的二叉树结点信息");
scanf_s("%c", &x);
p = Search(root, x);
if (p==NULL)
{
cout << "no found" << endl;
}
else
{
cout << "element is" << p->data << endl;
}
cout << CountLeaf(root) << endl;
cout << Depth(root) << endl;
}