#include<iostream>#include<queue>usingnamespace std;int child[105][3];int n;int ans =1;intmain(){
cin >> n;int x, y;for(int i =1; i < n; i++){
cin >> x >> y;if(!child[x][1])
child[x][1]= y;else
child[x][2]= y;}
queue<int>q;
q.push(1);while(!q.empty()){int len = q.size();
ans =max(ans, len);for(int i =0; i < len; i++){int t = q.front();
q.pop();if(child[t][1])
q.push(child[t][1]);if(child[t][2])
q.push(child[t][2]);}}
cout << ans;return0;}
二叉树的遍历运算
#include<iostream>#include<cstring>usingnamespace std;typedefstructT{char data;structT* left,* right;}Tnode,* Treenode;
Treenode created(int n,char* str1,char* str2){
Treenode s;int i =0;
s =new Tnode;if(n ==0)returnNULL;
s->data = str1[0];for(i =0; i < n; i++){if(str2[i]== str1[0])break;}
s->left =created(i, str1 +1, str2);//左
s->right =created(n - i -1, str1 + i +1, str2 + i +1);/*n - i - 1 表示右子树节点个数,str1 + i + 1 表示右子树前序遍历序列,
str2 + i + 1 表示右子树中序遍历序列。*/
cout << s->data;return s;}intmain(){char str1[35], str2[35];
cin >> str1;
cin >> str2;int len =strlen(str1);created(len, str1, str2);return0;}
二叉树的直径
#include<iostream>usingnamespace std;int n, f[200][3], ans =0;intdfs(int root){if(!root)return0;int l =dfs(f[root][1]);int r =dfs(f[root][2]);int len =max(l, r)+1;
ans =max(ans, l + r);return len;}intmain(){
cin >> n;for(int i =1; i < n; i++){int x, y;
cin >> x >> y;if(!f[x][1])
f[x][1]= y;else
f[x][2]= y;}dfs(1);
cout << ans;return0;}