我用了2种方法,1.递归,2.非递归(层次遍历)
#include<iostream>
using namespace std;
typedef struct BiNode {
char data;
struct BiNode* lchild, * rchild;
}BiNode, * BiTree;
typedef struct stack {
BiTree data[1024];
int top;
}stack;
typedef struct queue {
BiTree data[1024];
int front;
int rear;
}queue;
void create(BiTree& t) {//二叉树先序
char ch;
cin >> ch;
if (ch == '@')t = NULL;
else {
t = new BiNode;
t->data = ch;
create(t->lchild);
create(t->rchild);
}
}
void preorder(BiTree t) {
BiTree s[1024];
int top = 0;
BiTree p = t;
while (p || top != 0) {
if (p) {
s[top++] = p;
cout << p->data;
p = p->lchild;
}
else {
p = s[--top];
p = p->rchild;
}
}
}
void inorder(BiTree t) {
BiTree s[1024];
int top = 0;
BiTree p = t;
while (p || top != 0) {
if (p) {
s[top++] = p;
p = p->lchild;
}
else {
p = s[--top];
cout << p->data;
p = p->rchild;
}
}
}
int Btdepth(BiTree T) {
BiTree q[1024];
int front = 0, rear = 0;
BiTree p = T;
q[rear++] = p;
int level = 0;
int last = rear;
while (front < rear) {
p = q[front++];
if (p->lchild)q[rear++] = p->lchild;
if (p->rchild)q[rear++] = p->rchild;
if (front == last) {
level++;
last = rear;
}
}
return level;
}
int douNode(BiTree t) {
if (!t)return true;//空树为满二叉树
BiTree q[1024];
int num = 0;
int front = 0, rear = 0;
BiTree p = t;
q[rear++] = p;
while (front != rear) {
p = q[front++];
if (p->lchild && p->rchild)num++;
if (p->lchild)q[rear++] = p->lchild;
if (p->rchild)q[rear++] = p->rchild;
}
return num;
}
int DsonNodes(BiTree t) {//递归
if (t == NULL)return 0;
if (t->lchild && t->rchild)return DsonNodes(t->lchild) + DsonNodes(t->rchild) + 1;
else return DsonNodes(t->lchild) + DsonNodes(t->rchild);
}
int main() {
BiTree t;
create(t);//测试数据:1.abd@@e@@c@@ 2.ABD@F@@@CE@@@
//abcde先序
//edcba中序
/* preorder(t);
inorder(t);*/
/*cout << douNode(t);*/
cout << DsonNodes(t);
}