Diameter of Binary Tree
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].
/**
* 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 {
public:
int ans=0;
int anothergetlength(TreeNode*root){
if(root==NULL){
return 0;
}
int left=anothergetlength(root->left);
int right=anothergetlength(root->right);
ans=max(ans,left+right);
return left>right?(left+1):(right+1);
}
int diameterOfBinaryTree(TreeNode* root) {
anothergetlength(root);
return ans;
}
};
这个问题巧妙在private那里
1,首先要明确最长的路径并不一定过根节点,自己想的那种求左右子树之和加起来就不行了
2,其次要在private函数里求出各个子树的长度,其实在平常的求长度那里也只这么算的,但之前只是用来求最大长度就扔了,现在我们用一行代码把这些信息利用起来
3,此外,路径数==节点数-1
4,ans要定义为全局变量
ans = max(ans, left+right + 1);//这个语句实际上就实现了求最大值
//若最长路径在左子树中而不经过根节点,这条语句可以挑出这个最大值