Given a binary tree, you need to compute thelengthofthe diameter ofthe tree. The diameter ofa binary tree is thelengthofthe longest path between anytwo nodes ina tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
23
/ \
45
Return 3, which is thelengthofthe path [4,2,1,3] or [5,2,1,3].
classSolution {public:
int sumpath = 0;
int diameterOfBinaryTree(TreeNode* root) {
dfs(root);
return sumpath;
}
int dfs(TreeNode* root){
if(root == NULL) return0;
int leftpath = dfs(root->left);
int rightpath =dfs(root->right);
if(leftpath + rightpath > sumpath)
sumpath = leftpath + rightpath;
return max(leftpath +1, rightpath + 1);
}
};