80分c++求调(有注释)
查看原帖
80分c++求调(有注释)
1267350
red_right_hand楼主2024/7/26 17:30

代码如下:

#include<bits/stdc++.h>
using namespace std;
typedef struct Node {
	struct Node* left;//左子节点
	struct Node* right;//右子节点
	int depth;//深度
} N;
int main() {
	int n;//节点数量
	cin>>n;//输入节点数
	N nodes[n];//有n个节点的数组(存储节点)
	int L,R;//临时变量
	int M_D=0;//最大深度
	for(int i=0; i<n; i++) {
		cin>>L>>R;//输入左子节点和右子节点
		if(R==0) {//判右边叶子
			nodes[i].right=NULL;
		}
		else {//指向右子节点+规定右子节点深度
			nodes[i].right= &nodes[R-1];
        nodes[i].right->depth=nodes[i].depth+1;
		}
		if(L==0) {//判左边叶子
			nodes[i].left=NULL;
		}
		else {//指向左子节点+规定左子节点深度
			nodes[i].left= &nodes[L-1];
			nodes[i].left->depth=nodes[i].depth+1;
      }
		if(i==0) {//判根节点
			nodes[i].depth=1;
		}
		if(nodes[i].depth>M_D) {//判断最大深度
			M_D=nodes[i].depth;
		}
	}
	cout<<M_D;//输出最大深度
	return 0;
}

请大佬指点

2024/7/26 17:30
加载中...