题目描述:
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.
思路:后序遍历,函数int postorder(TreeNode* node, int& res)中,res存放遍历过程中最长路径,返回值是到大当前节点的最长路径。
代码:
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
if (root==NULL)
return 0;
int res=0;
postorder(root,res);
return res-1;
}
int postorder(TreeNode* node, int& res)
{
if (node==NULL)
return 0;
int maxl=postorder(node->left,res);
int maxr=postorder(node->right, res);
if (res<maxl+maxr+1)
res=maxl+maxr+1;
return max(maxl,maxr)+1;
}
};
本文介绍了一种通过后序遍历方法来计算二叉树直径的有效算法。该算法利用递归特性,在遍历过程中更新最长路径,最终找到二叉树中最长路径的长度。
543

被折叠的 条评论
为什么被折叠?



