Ask your own question, for FREE!
Computer Science 17 Online
OpenStudy (anonymous):

find an algorithm for diameter of a tree in O(n). the answer i find is this but i dont know how does it work. int diameter2(TreeNode t, int* height) { int lh = 0, rh = 0; int leftD = 0, rightD = 0; if(t == NULL) { *height = 0; return 0; /* diameter is also 0 */ } leftD = diameter2(root->left, &lh); rightD = diameter2(root->right,&rh); /* Height of current node is max of heights of left and right subtrees plus 1*/ *height = max(lh, rh) + 1; return max(lh + rh + 1, leftD, rightD); } tnx for ur help.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!