按先序遍历序列建立一个二叉树的二叉链表,统计二叉树中叶子结点个数和二叉树的深度。
测试输入
-+a##*b##c##/d##e##↵
期待的输出
leafs=5↵
Depth=4↵
#include<iostream>
#include<string>
#include<cstdio>
using namespace std;
int max(int a, int b)
{
if (a >= b)
return a;
else
return b;
}
class binarytreenode {
public:
char data;
binarytreenode * Lchild, * Rchild;
binarytreenode() { Lchild = NULL; Rchild = NULL; }
};
class binarytree {
public:
binarytreenode * root;
binarytree() { root =NULL; }
void createtree( binarytreenode * &p)
{
char ch;
cin >> ch;
if (ch == '\n')
return;
if (ch == '#')
p = NULL;
else
{
p = new binarytreenode();
if (!p)
exit(-1);
p->data = ch;
createtree(p->Lchild);
createtree(p->Rchild);
return;
}
}
int depth(binarytreenode *p)
{
if (p == NULL)
return 0;
else
return 1 + max(depth(p->Lchild), depth(p->Rchild));
}
int leaf(binarytreenode *p)
{
if (p == NULL) return 0;
if (p->Lchild == NULL && p->Rchild == NULL)
return 1;
if (p == NULL)
return -1;
else
{
return 0 + leaf(p->Lchild) + leaf(p->Rchild);
}
}
};
bool similar(binarytreenode *t1, binarytreenode *t2)
{
bool leftS = false, rightS = false;
if (t1 == NULL && t2 == NULL) // 两树皆空
return true;
else if (t1 == NULL || t2 == NULL) // 只有一个树为空
return false;
else // 递归地进行判断
{
leftS = similar(t1->Lchild, t2->Lchild);
rightS = similar(t1->Rchild, t2->Rchild);
return leftS && rightS;
}
}
int main()
{
binarytree x, t;
x.createtree(x.root);
int leaf1, depth1;
depth1 = x.depth(x.root);
leaf1 = x.leaf(x.root);
cout << "leafs=" << leaf1 << endl;
cout << "Depth=" << depth1 << endl;
} ```