Skip to content

Commit 206d2c3

Browse files
diameter of btree
1 parent 186152e commit 206d2c3

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

week2/diameter-of-binary-tree.c

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// Simple implementation of max from stack
2+
#define max(a,b) \
3+
({ __typeof__ (a) _a = (a); \
4+
__typeof__ (b) _b = (b); \
5+
_a > _b ? _a : _b; })
6+
7+
/**
8+
* Definition for a binary tree node.
9+
* struct TreeNode {
10+
* int val;
11+
* struct TreeNode *left;
12+
* struct TreeNode *right;
13+
* };
14+
*/
15+
16+
17+
int diameterOfBinaryTree(struct TreeNode* root) {
18+
// Special cases
19+
if (root == NULL || root->left == NULL && root->right == NULL) {
20+
return 0;
21+
}
22+
23+
int highestSum = 0;
24+
int longestDistance = longest(root, &highestSum) - 1; // Subtract 1 for root
25+
26+
return max(longestDistance, highestSum);
27+
}
28+
29+
/**
30+
* Return longest distance for one node
31+
*/
32+
int longest(struct TreeNode* node, int* highestSum) {
33+
int right = 0, left = 0;
34+
35+
if (node->left != NULL) {
36+
left = longest(node->left, highestSum);
37+
}
38+
if (node->right != NULL) {
39+
right = longest(node->right, highestSum);
40+
}
41+
42+
// Maintain highest sum
43+
if (right + left > (*highestSum)) {
44+
*highestSum = right + left;
45+
}
46+
47+
return (max(left, right) + 1);
48+
}

0 commit comments

Comments
 (0)