543. Diameter of Binary Tree【Easy】【二叉树的直径】

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.

Accepted
111,412
Submissions
241,330
【解析】:
对于每一个点,left 和 right depth 之和,就等于这个点的最大直径。换一句话说,就是这个点,左边能延伸出去最大值 + 右边能延伸出去的最大值,加一起,就等于这个点的左边最远的点到右边最远的点的距离。 就是最大直径。

关键点:用post order去返回每一个点的depth(在之前depth值上+1),null点就返回0(base case);

    需要两个function,因为getDepth function 返回的都是depth,不是diameter,所以需要diameterOfBinaryTree 来单独返回diameter;

    每一个点的最大直径等于左边的depth 加上 右边的depth,取所有点中最大的值。

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int res = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        getDepth(root);
        return res;
    }
    public int getDepth(TreeNode root) {
        if(root == null) return 0;
        int l = getDepth(root.left);
        int r = getDepth(root.right);
        res = Math.max(res,l+r);
        return Math.max(l,r) + 1;
    }
}

猜你喜欢

转载自www.cnblogs.com/Roni-i/p/10434918.html
今日推荐