题目:https://pintia.cn/problem-sets/994805342720868352/problems/994805355987451904
大致题意就是给出一个序列,构造一棵二叉查找树,输出最大深度和次最大深度的结点个数之和。
方法一,BFS
1 #include<iostream> 2 #include<unordered_map> 3 #include<queue> 4 #include<algorithm> 5 using namespace std; 6 7 struct Node { 8 int data,level; 9 Node* lchild; 10 Node* rchild; 11 }; 12 13 void insert(Node *&root,int data) { 14 if(root == NULL) { 15 root = new Node; 16 root->data = data; 17 root->lchild = root->rchild = NULL; 18 } else if(data <= root->data) insert(root->lchild,data); //此题BST定义 19 else insert(root->rchild,data); 20 } 21 22 unordered_map<int,int> mp; 23 int maxlevel = -1; 24 void BFS(Node* root) { 25 queue<Node*> q; 26 root->level = 1; 27 q.push(root); 28 while(!q.empty()) { 29 Node* node = q.front(); 30 mp[node->level]++; 31 maxlevel = max(maxlevel,node->level); 32 q.pop(); 33 if(node->lchild != NULL) { 34 node->lchild->level = node->level+1; 35 q.push(node->lchild); 36 } 37 if(node->rchild != NULL) { 38 node->rchild->level = node->level+1; 39 q.push(node->rchild); 40 } 41 } 42 } 43 int main() { 44 int n,t; 45 cin>>n; 46 Node* root = NULL; 47 for(int i = 0; i < n; ++i) { 48 cin>>t; 49 insert(root,t); 50 } 51 BFS(root); 52 printf("%d + %d = %d",mp[maxlevel],mp[maxlevel-1],mp[maxlevel]+mp[maxlevel-1]); 53 return 0; 54 }
方法二,DFS
1 #include<iostream> 2 #include<unordered_map> 3 #include<queue> 4 #include<algorithm> 5 using namespace std; 6 7 struct Node { 8 int data,level; 9 Node* lchild; 10 Node* rchild; 11 }; 12 13 void insert(Node *&root,int data) { 14 if(root == NULL) { 15 root = new Node; 16 root->data = data; 17 root->lchild = root->rchild = NULL; 18 } else if(data <= root->data) insert(root->lchild,data); //此题BST定义 19 else insert(root->rchild,data); 20 } 21 22 unordered_map<int,int> mp; 23 int maxlevel = -1; 24 void DFS(Node* root,int level) { 25 if(root == NULL) { 26 maxlevel = max(maxlevel,level-1); 27 return; 28 } 29 mp[level]++; 30 DFS(root->lchild,level+1); 31 DFS(root->rchild,level+1); 32 } 33 int main() { 34 int n,t; 35 cin>>n; 36 Node* root = NULL; 37 for(int i = 0; i < n; ++i) { 38 cin>>t; 39 insert(root,t); 40 } 41 DFS(root,1); 42 printf("%d + %d = %d",mp[maxlevel],mp[maxlevel-1],mp[maxlevel]+mp[maxlevel-1]); 43 return 0; 44 }