版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_24133491/article/details/86501783
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.
题意:返回一颗二叉树的最长直径,直径定义为任意两个结点之间的边的数量;
解法:一颗二叉树的最长直径必然是其左子树的最大深度加上右子树的最大深度;因此,这道题目其实就是让我们求解二叉树的深度的问题;
Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int diameterOfBinaryTree(TreeNode root) {
if (root == null) return 0;
int res = depth(root.left) + depth(root.right);
res = Math.max(res, diameterOfBinaryTree(root.left));
res = Math.max(res, diameterOfBinaryTree(root.right));
return res;
}
private int depth(TreeNode root) {
if (root == null) return 0;
int left = depth(root.left);
int right = depth(root.right);
return Math.max(left, right) + 1;
}
}