问题描述:
Given the root of a binary tree, return 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.
The length of a path between two nodes is represented by the number of edges between them.
思路:
最长路径(diameter)分两种情况:
case 1: 最长路径跨越根节点:左子树高度+右子树高度+2
case 2:最长路径不跨越根节点:拆成两个子问题,分别以左右孩子为根,求较大者
最终结果=max(case1,case2)
代码如下:
class Solution {
public int diameterOfBinaryTree(TreeNode root) {
if(root==null) return 0;
int leftHeight=height(root.left); //height of the left subtree
int rightHeight=height(root.right); //height of the right subtree
int leftDiameter=diameterOfBinaryTree(root.left); //diameter of the left subtree
int rightDiameter=diameterOfBinaryTree(root.right); //diameter of the right subtree
//case 1: cross the root, then longest path = leftHeight+rightHeight+2
//case 2: do not cross the root, the longest path = max (diameter of left, diameter of right)
//we need to calculate the maximum of the two cases
return Math.max(leftHeight+rightHeight+2, Math.max(leftDiameter, rightDiameter));
}
private int height(TreeNode root){
if(root==null) return -1;
return Math.max(height(root.left), height(root.right))+1;
}
}
时间复杂度: O(n)