543. Diameter of Binary Tree

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

tree

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.

Solution

DFS

以每个节点为起点,往左右两边扩展,更新diameter。

这里用到一个depth方法用作辅助,但是这个depth的定义跟惯用的定义不太一样,对于leaf节点depth是1,对于root节点则是root到最深leaf的距离+1。

这道题唯一要注意的就是值不要弄错了。

/**
 * 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 path = depth(root.left) + depth(root.right);
        int leftPath = diameterOfBinaryTree(root.left);
        int rightPath = diameterOfBinaryTree(root.right);
        
        return Math.max(path, Math.max(leftPath, rightPath));
    }
    
    public int depth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        return 1 + Math.max(depth(root.left), depth(root.right));
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 十年前我们在济南的一家三甲医院实习,那是在我们山东很有名望的一家医院,可谓是百年老院、大医精诚。那时候二十出头的我...
    范范的范阅读 276评论 0 0
  • 忆平泉杂咏-忆春耕 唐-李德裕 郊外杏花坼,林间布谷鸣。 原田春雨后,谿水夕流平。 野老荷蓑至,和风吹草轻。 无因...
    悦图文阅读 584评论 4 3
  • 大学每到考试周,心里就开始犯嘀咕,该用怎样的复习方法最好,我觉着所有的方法都只是借鉴,最好的方法还是要自己寻找,身...
    岁月斑驳叶无痕阅读 277评论 0 0
  • 你为什么不开心呢 …… 请再往前走三步好吗 那个时候 我会微笑着给你一个拥抱 其实 我一直在那里等你啊
    ii南有乔木阅读 244评论 7 5