File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments