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
6
7 > 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.
题意:叶子节点的最长距离(可不经过根节点)。
做完二叉树的总结竟然经过自己独立并且一遍AC了!太开心了!果然老外的教程还是比较靠谱的,都怪自己的英语水平还达不到流畅地阅读,继续加油~
做的思路是这样子的,以root为根节点,计算root左子树根节点(root->left)到叶子节点的最长距离(由countPath辅助完成),再加上root右子树根节点(root->right)到右子树叶子节点的最长距离,这两个距离相加后再加上1(root本身)之后就是以root为根节点的叶子节点间的最长距离。
然后遍历整棵树的所有节点,用ans为来维护最大值。遍历完后ans就是答案了。
具体代码如下:
1 | // |