当前位置: 代码迷 >> 综合 >> 2018-2
  详细解决方案

2018-2

热度:125   发布时间:2023-10-14 06:30:20.0
/* 2020/4/16 二刷 */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<vector>
using namespace std;int N;
int input[100][4];
int maxNum = 0;
int maxHeight = 0;
typedef struct node
{
    int id;int height;int numChild;node* lchild;node* mchild;node* rchild;
}Node,*Tree;int max(int a,int b)
{
    if(a>b) return a;else return b;
}Node* newNode(int id)
{
    Node* temp = (Node*)malloc(sizeof(Node));temp->id = id;temp->height = 0;temp->numChild = 0;temp->lchild = NULL;temp->mchild = NULL;temp->rchild = NULL;return temp;
}void createTree(Node* root)
{
    int i = 0;int numChild = 0;for(i = 0;i<N;i++){
    if(root->id == input[i][0]){
    break;}}if(i == N) return;if(input[i][1]){
    numChild++;Node* temp1 = newNode(input[i][1]);root->lchild = temp1;createTree(temp1);}if(input[i][2]){
    numChild++;Node* temp2 = newNode(input[i][2]);root->mchild = temp2;createTree(temp2);}if(input[i][3]){
    numChild++;Node* temp3 = newNode(input[i][3]);root->rchild = temp3;createTree(temp3);}root->numChild = numChild;
}int treeHeight(Node* root)
{
    int L,M,R,height;if(root){
    L = treeHeight(root->lchild);M = treeHeight(root->mchild);R = treeHeight(root->rchild);height = max(L,max(M,R)) + 1;return height;}elsereturn 0;
}void preOrderGetHeight(Node* root)
{
    if(root){
    root->height = treeHeight(root);preOrderGetHeight(root->lchild);preOrderGetHeight(root->mchild);preOrderGetHeight(root->rchild);}
}vector<Node*> v;
void preOrderGetSequence(Node* root)
{
    if(root){
    if(root->numChild==maxNum)v.push_back(root);preOrderGetSequence(root->lchild);preOrderGetSequence(root->mchild);preOrderGetSequence(root->rchild);}
}int main()
{
    scanf("%d",&N);for(int i = 0;i<N;i++){
    int tempNum = 0;scanf("%d%d%d%d",&input[i][0],&input[i][1],&input[i][2],&input[i][3]);if(input[i][1]!=0) tempNum++;if(input[i][2]!=0) tempNum++;if(input[i][3]!=0) tempNum++;if(tempNum>maxNum) maxNum = tempNum;}Node* root = newNode(input[0][0]);createTree(root);preOrderGetHeight(root);preOrderGetSequence(root);int index = -1;for(int i = 0;i<v.size();i++){
    if(v[i]->height > maxHeight){
    index = i;maxHeight = v[i]->height;}}printf("%d\n",v[index]->id);return 0;
}
  相关解决方案