pat甲级 1115 Counting Nodes in a BST (30分)
note:常规题,一般思路:建树+搜索(DFS/BFS),至于怎么建树,怎么搜索就不细说了,很多数据结构教科书例如清华殷人昆(C语言),清华邓俊辉(c++)都有非常经典的函数代码,思想其实一样。
优化思路:搜索过程均是沿着树向下搜索:DFS以深度为标尺,每次都向更深的子树下探,直到叶节点然后回退;BFS是一层一层向下搜索,遍历完一层再搜索下一层。因此搜索的过程其实是把整个树重复走了一遍,那么,可以不要搜索过程直接在建树的同时记录各节点的深度。
代码如下(只有建树函数);
#include <iostream>
using namespace std;
int num[1001]={0},maxdepth=-1;
struct node
{
int data;
node(int _data) {data=_data;}//构造函数,初始化;oj未写析构函数,因为ac后oj自动刷新,但做项目时一定要写
node *lchild=NULL,*rchild=NULL;//初始化
};
void Insert(node *&Root,int data,int depth)//引用符&必须带
{
if(Root==NULL)
{
Root=new node(data);//修改Root,因此必带引用&
++num[depth];
maxdepth= depth>maxdepth?depth:maxdepth;//也可以用max函数
}
else if(Root->data < data) Insert(Root->rchild,data,depth+1);//右子树递归
else Insert(Root->lchild,data,depth+1); //左子树递归
}
int main()
{
int n,temp;
node *Root=NULL;
cin>>n;
for(int i=0;i<n;++i)
{
cin>>temp;
Insert(Root,temp,0);
}
printf("%d + %d = %d",num[maxdepth],num[maxdepth-1],num[maxdepth]+num[maxdepth-1]);
return 0;
}