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.

Divide and Conquer

Time Complexity
O(N)
Space Complexity
O(logn)

思路

这题做的时候发现应该用Divide and Conquer,最长的一条线肯定是左边最长的长度加上右边最长的长度加上根节点自己,但是如果每一个点都用分治法这么做,返回上来的不是从根节点出发的一条直线。
所以这里要引入一个global max,只有取global max的时候做这个操作,其余的是返回是左右的较大的加上自己,这样子返回的才是一条直线。在取max的时候,因为这题是要算边的个数,所以不用加上自己

代码

private int max = 0;
public int diameterOfBinaryTree(TreeNode root) {
    if(root == null) return 0;
    helper(root);
    return max;
}
public int helper(TreeNode root){
    if(root == null) return 0;
    int left = helper(root.left);
    int right = helper(root.right);
    
    max = Math.max(left + right, max);
    
    return Math.max(left, right) + 1;
}

annielulu
5 声望5 粉丝

引用和评论

0 条评论