1115 Counting Nodes in a BST

news/2024/7/3 7:00:27

我的DFS

void DFS(Node* root){if(root==NULL)return;if(root->lchild){root->lchild->layer = root->layer+1;cnt[root->lchild->layer] ++;maxLayer = max(maxLayer,root->lchild->layer);DFS(root->lchild);}if(root->rchild){root->rchild->layer = root->layer+1;cnt[root->rchild->layer] ++;maxLayer = max(maxLayer,root->rchild->layer);DFS(root->rchild);}
}

柳婼仙女的DFS

void DFS(Node* root,int depth){if(root==NULL){maxLayer = max(maxLayer,depth);return;}cnt[depth] ++;DFS(root->lchild,depth+1);DFS(root->rchild,depth+1);
}

注意:对左右子结点进行DFS之前不可以判空,否则maxLayer永不会更新!

AC代码

#include<cstdio>
#include<iostream>
#include<set>
#include<vector>
#include<map>
#include<algorithm>
#include<cmath>
#include<queue>using namespace std;const int maxn = 1001;int n;
int cnt[maxn] = {0};
int maxLayer = -1;struct Node{int v;Node *lchild,*rchild;
};void insert(Node* &root,int x){if(root==NULL){root = new Node;root->v = x;root->lchild = root->rchild = NULL;return;}if(x<=root->v)insert(root->lchild,x);if(x>root->v)insert(root->rchild,x);
}void DFS(Node* root,int depth){if(root==NULL){maxLayer = max(maxLayer,depth);return;}cnt[depth] ++;DFS(root->lchild,depth+1);DFS(root->rchild,depth+1);
}int main(){cin>>n;Node* root = NULL;for(int i=0;i<n;i++){int x;cin>>x;insert(root,x);}DFS(root,0);printf("%d + %d = %d\n",cnt[maxLayer-1],cnt[maxLayer-2],cnt[maxLayer-1]+cnt[maxLayer-2]);return 0;
}


http://lihuaxi.xjx100.cn/news/240840.html

相关文章

CSS控制字体在一行内显示不换行

当一行文字超过DIV或者Table的宽度的时候&#xff0c;浏览器中默认是让它换行显示的&#xff0c;如果不想让他换行要怎么办呢&#xff1f;用CSS让文字在一行内显示不换行的方法&#xff1a; 一般的文字截断(适用于内联与块)&#xff1a; 1 .text-overflow { 2 display:bloc…

Linux下des对称性加密

最近对接公安审计一些经历 对方的需求&#xff1a; 打成zip包对zip包进行des-cbc对称性加密&#xff0c;使用约定好的 -K和-iv值比如 -K "abcd$#!" -iv "efgh$#!"加密后做base64编码起初是想尝试用 php 去做&#xff0c;经过一阵折腾之后发现&#xff0c;p…

1062 最简分数

注意点&#xff1a; 1. 对两个分数之间的理解&#xff0c;这应该是一个开区间而不是闭区间 2. 读入的时候用 scanf("%d/%d %d/%d %d",&N1,&M1,&N2,&M2,&K) 不可以&#xff0c;分号前后会被视为一个整体。 AC代码 #include<cstdio> #i…

linux系统开机静态分配ip地址

在/etc/sysconfig/network-scripts/ifcfg-eth0文件中 添加&#xff1a; IPADDR192.168.1.100&#xff08;设置静态地址&#xff09; NETMASK255.255.255.0&#xff08;设置子网掩码&#xff09; GATEWAY192.168.1.1&#xff08;设置网关地址&#xff09; 修改&#xff1a; BOOT…

C#图片处理常见方法性能比较

在.NET编程中&#xff0c;由于GDI的出现&#xff0c;使得对于图像的处理功能大大增强。在文通过一个简单黑白处理实例介绍在.NET中常见的图片处理方法和原理并比较各种方法的性能。 黑白处理原理&#xff1a;彩色图像处理成黑白效果通常有3种算法&#xff1b; (1).最大值法: 使…

1081 Rational Sum 有理数类型题处理 需再做

一、有理数结构体的几个约束 struct fraction{LL up,down;fraction(LL _up,LL _down):up(_up),down(_down){} }; &#xff08;1&#xff09;如果这个有理数是0&#xff0c;则让分子为0&#xff0c;分母为1(这方便后来输出时归于整数一类) &#xff08;2&#xff09;如果这个…

Java springMVC POI 导出 EXCEL

2019独角兽企业重金招聘Python工程师标准>>> 思路 &#xff1a; 将需要导出的数据存放在一个List中创建一个EXCEL表 注意 XSSFWorkbook 只能操作2007以上的版本&#xff0c;XSSFWorkbook 只能操作2003一下的版本&#xff0c;所以需要的时候可以使用 Workbook创建对象…

1088 Rational Arithmetic

本题需要具备有理数处理相关知识。 本次收获(错点) &#xff08;1&#xff09;在化简求最大公约数时&#xff0c;忘记给传入的分子加绝对值 &#xff08;2&#xff09;把除法错写成乘法&#xff0c;自己设计测试用例才测出orz AC代码 #include<cstdio> #include<…