/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */
intgetHeight(struct TreeNode* root) { int left, right, max; if(root) { left = getHeight(root->left); right = getHeight(root->right); max = left > right ? left:right; return max + 1; } return0; }
intmax(int a, int b) { if(a > b) return a; else return b; }
intdiameterOfBinaryTree(struct TreeNode* root) { if(!root) return0; int result = getHeight(root->left) + getHeight(root->right); return max(result, max(diameterOfBinaryTree(root->left), diameterOfBinaryTree(root->right))); }
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */
intcalMax(struct TreeNode* root, int *result) { if (NULL == root) return0; //计算左子树的高度和最大直径 int left = calMax(root->left, result); //计算右子树的高度和最大直径 int right = calMax(root->right, result); //更新最大直径 if (left + right > *result) *result = left + right; //返回二叉树高度 return (left > right ? left : right) + 1; }
intdiameterOfBinaryTree(struct TreeNode* root) { int result = 0; //需要传result的地址 calMax(root, &result); return result; }