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
  • 憶平泉雜詠-憶春耕 唐-李德裕 郊外杏花坼,林間布谷鳴。 原田春雨后,谿水夕流平。 野老荷蓑至,和風吹草輕。 無因...
    悅圖文閱讀 580評論 4 3
  • 大學每到考試周,心里就開始犯嘀咕,該用怎樣的復習方法最好,我覺著所有的方法都只是借鑒,最好的方法還是要自己尋找,身...
    歲月斑駁葉無痕閱讀 277評論 0 0
  • 你為什么不開心呢 …… 請再往前走三步好嗎 那個時候 我會微笑著給你一個擁抱 其實 我一直在那里等你啊
    ii南有喬木閱讀 244評論 7 5