数据结构有序树转二叉树(树的遍历)

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

数据结构有序树转⼆叉树(树的遍历)
Description
计算输⼊有序树的深度和有序树转化为⼆叉树之后树的深度。

Input
输⼊包含多组数据。

每组数据第⼀⾏为⼀个整数n(2<=n<=30000)代表节点的数量,接下来n-1⾏,两个整数a、b代表a是b的⽗亲结点。

Output
输出当前树的深度和转化成⼆叉树之后的深度。

Sample Input
5
1 5
1 3
5 2
1 4
Sample Output
3 4
HINT
Append Code
析:这个题很好说,只要遍历⼀次就能得到答案,由于要先有序树转成⼆叉树,我也没听过,我百度了⼀下怎么转,看到百度百科中有,我总结⼀下就是,左⼉⼦,
右兄弟,和那个字典树有的⼀拼,也就是左结点是⼉⼦结点,⽽右结点是兄弟结点,那么我们可以⽤两个参数来记录深度,⼆叉树既然是右兄弟,那么同⼀深度的就会多⼀层,
加1,这样最⼤的就是答案。

代码如下:
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <cmath>
#include <stack>
#define debug puts("+++++")
//#include <tr1/unordered_map>
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std;
//using namespace std :: tr1;
typedef long long LL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const double inf = 0x3f3f3f3f3f3f;
const LL LNF = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 3e4 + 5;
const LL mod = 1e3 + 7;
const int N = 1e6 + 5;
const int dr[] = {-1, 0, 1, 0, 1, 1, -1, -1};
const int dc[] = {0, 1, 0, -1, 1, -1, 1, -1};
const char *Hex[] = {"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"}; inline LL gcd(LL a, LL b){ return b == 0 ? a : gcd(b, a%b); }
inline int gcd(int a, int b){ return b == 0 ? a : gcd(b, a%b); }
inline int lcm(int a, int b){ return a * b / gcd(a, b); }
int n, m;
const int mon[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const int monn[] = {0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
inline int Min(int a, int b){ return a < b ? a : b; }
inline int Max(int a, int b){ return a > b ? a : b; }
inline LL Min(LL a, LL b){ return a < b ? a : b; }
inline LL Max(LL a, LL b){ return a > b ? a : b; }
inline bool is_in(int r, int c){
return r >= 0 && r < n && c >= 0 && c < m;
}
vector<int> G[maxn];
bool in[maxn];
int ans1, ans2;
void dfs(int u, int cnt1, int cnt2){
ans1 = Max(ans1, cnt1);
ans2 = Max(ans2, cnt2);
for(int i = 0; i < G[u].size(); ++i)
dfs(G[u][i], cnt1+1, cnt2+i+1);
}
int main(){
while(scanf("%d", &n) == 1){
for(int i = 0; i <= n; ++i) G[i].clear(), in[i] = 0;
int u, v;
for(int i = 1; i < n; ++i){
scanf("%d %d", &u, &v);
G[u].push_back(v);
in[v] = true;
}
ans1 = ans2 = 0;
for(int i = 1; i <= n; ++i) if(!in[i]){
dfs(i, 1, 1); break;
}
printf("%d %d\n", ans1, ans2);
}
return 0;
}。

相关文档
最新文档