Diameter of N-Ary Tree

void get_max_level(struct Node * nd, int *lvl, int *max_d){
int curlvl = *lvl;
int ii, m1 = 0, m2 =0;
if (!nd)
/* return if no children */
if (!(nd->numChildren))
int clvl;
/* get each child height */
for (ii=0; ii<nd->numChildren; ii++){
clvl = 0;
get_max_level(nd->children[ii], &clvl, max_d);
/* save max 2 height values */
if (m1 < clvl){
m2 = m1;
m1 = clvl;
else if (m2 < clvl)
m2 = clvl;
if ((*max_d) < (m2+m1))
*max_d = (m2+m1);

(*lvl) += m1;
int* diameter(struct Node* root) {
int lvl = 0, maxd = 0;
get_max_level(root, &lvl, &maxd);
if (maxd < lvl) return lvl-1;
return maxd;





Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to investigate a problem

How we prevented missing SQL indexes

Build a Binary Clock with Elixir and Nerves

LeetCode 1225. Report Contiguous Dates

Why Developers should pay attention to Flutter in 2020 App Development

Things you need to know before building an app

Software over hardware

Insights of the Worldwide Developers Community

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store



More from Medium

Make a copy of a LinkedList with next and random pointer

A journey into sorting algorithms — Part I

Photo by Tom Swinnen from Pexels

[LeetCode] (Easy) 70. Climbing Stairs

How I write my algorithms for CP