标签:right PAT BST tree pos dfs int left
1115 Counting Nodes in a BST
题目
https://pintia.cn/problem-sets/994805342720868352/problems/994805355987451904
题意
将给定数字放入二叉搜索树中,并输出最低两层的结点数量及其总和
代码解析
建树的insert函数就是常规流程
判断结点数有两种方式——dfs和bfs,这两个方法都能AC
AC代码
#include<bits/stdc++.h>
using namespace std;
typedef struct node* tree;
struct node{
int data;
tree left,right;
};
tree insert(tree a,int t)
{
if(!a)
{
a=new node();
a->data=t;
a->left=a->right=NULL;
return a;
}
else if(t<=a->data)
a->left=insert(a->left,t);
else
a->right=insert(a->right,t);
return a;
}
vector<int> ans(1005,0);
int pos=0;
void bfs(tree a)
{
queue<tree> q;
q.push(a);
tree last=q.back();
while(q.size())
{
tree b=q.front();
q.pop();
ans[pos]++;
if(b->left) q.push(b->left);
if(b->right) q.push(b->right);
if(b==last)
{
pos++;
last=q.back();
}
}
}
//void dfs(tree a,int depth)
//{
// if(a==NULL)
// {
// pos=max(pos,depth);
// return;
// }
// ans[depth]++;
// dfs(a->left,depth+1);
// dfs(a->right,depth+1);
//}
int main()
{
int n,t;
tree a=NULL;
cin>>n;
while(n--)
{
cin>>t;
a=insert(a,t);
}
bfs(a);
// dfs(a,0);
int x=ans[pos-1],y=ans[pos-2];
printf("%d + %d = %d",x,y,x+y);
}
参考
dfs部分参考了1115. Counting Nodes in a BST (30)-PAT甲级真题(二叉树的遍历,dfs)
标签:right,PAT,BST,tree,pos,dfs,int,left 来源: https://blog.csdn.net/ljhsq/article/details/120159467
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。