Comment on page

# 543.Diameter of Binary Tree

543.Diameter of Binary Tree

1
/ \
2 3
/ \
4 5

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
int depth(TreeNode* root)
{
if(!root) return 0;
return 1+max(depth(root->left), depth(root->right));
}
public:
int diameterOfBinaryTree(TreeNode* root) {
if(!root || (!root->left && !root->right)) return 0;
//cout<<depth(root->left)<< "+" <<depth(root->right)<<endl;
int res=depth(root->left) +depth(root->right);
res=max(res,diameterOfBinaryTree(root->right));
res=max(res,diameterOfBinaryTree(root->left));
return res;
}
};

class Solution
{
public:
int diameterOfBinaryTree(TreeNode* root)
{
int distance = 0;
dfs(root, distance);
return distance;
}
/**
* distance 记录以root为根的子树的最大直径，返回树的高度
*/
int dfs(TreeNode *root, int &distance)
{
if (root == nullptr)
return 0;
int left = dfs(root->left, distance);
int right = dfs(root->right, distance);
distance = max(left + right, distance);
return max(left, right) + 1;
}
};