Description
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
Analysis
这道题我做了很久,原因是因为我一直想错了方向。
题意是要就我们找到最长路,一开始我想着如果要求最长路那么一定是经过根,然后求最长的深度左右子树的最长深度加起来就可以了。
后来才发现我没读懂题目,我一直以为题目中的不经过根没什么特别的意思,其实是有意思的。
我最后的做法就是利用递归,然后每次都将diameter 和 left+right来更新diameter最后得到结果。
Code
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
//wrong
class Solution {
public:
int depthTree(TreeNode* root){
if(root == NULL) return 0;
//if(root->left==NULL&& root->right==NULL) return 1;
TreeNode* right = root->right;
TreeNode* left = root->left;
return 1+max(depthTree(right),depthTree(left));
}
int diameterOfBinaryTree(TreeNode* root) {
if(root == NULL) return 0;
if(root->left==NULL&& root->right==NULL) return 0;
TreeNode* right = root->right;
TreeNode* left = root->left;
// if(root->left!=NULL&& root->right!=NULL) return 2+depthTree(left)+depthTree(right);
/*else*/ return depthTree(right)+depthTree(left);
}
};
//correct
class Solution {
public:
int depthTree(TreeNode* root, int& diameter) {
if(root == NULL) return 0;
int left=depthTree(root->left, diameter);
int right=depthTree(root->right, diameter);
diameter = max(diameter, left+right);
return 1+max(left,right);
}
int diameterOfBinaryTree(TreeNode* root) {
if(root == NULL) return 0;
int diameter = 0;
depthTree(root, diameter);
return diameter;
}
};