1. 程式人生 > >LeetCode 543. Diameter of Binary Tree (二叉樹的直徑)

LeetCode 543. Diameter of Binary Tree (二叉樹的直徑)

tween res edge public level 距離 sent java dot

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 longestpath 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.


題目標簽:Tree   這道題目給了我們一個二叉樹,讓我們找到二叉樹的直徑 - 最遠的距離存在於兩個點之間。 我們另外需要一個function - getDepth。 這個function利用post order,從最左邊下面開始返回每一個點的depth, 如果這個點是null,那麽返回0,依次像上一個level,每次加1。 在知道了每一個點的depth之後,我們可以來找到樹的最大直徑。我們來分析一下,怎麽找到最大直徑,取題目中給的例子,我們只看2 4 5 這基本結構, 2 4 5 這個子樹的最大直徑是2,這個直徑等於 2的left 4的depth(1) 和 2的right 5的depth(1),兩邊的depth之和就等於最大直徑 。 我們再回到原來的樹立,1,2,3,4,5這個原題中的例子,我們從下往上看, 4的depth = 1, 5的depth = 1, 對於每一個parent node 取兩個children的depth之和,和之前的diameter比較,大的就取代。 所以2的diameter = 2; 接著看2的depth = 2, 3的depth = 1, 那麽1的diameter = 2 + 1 = 3, 比之前的diameter大,所以最大直徑等於3。 對於每一個點,left 和 right depth 之和,就等於這個點的最大直徑。換一句話說,就是這個點,左邊能延伸出去最大值 + 右邊能延伸出去的最大值,加一起,就等於這個點的左邊最遠的點到右邊最遠的點的距離。 就是最大直徑。

Java Solution:

Runtime beats 72.26%

完成日期:06/30/2017

關鍵詞:Tree

關鍵點:用post order去返回每一個點的depth(在之前depth值上+1),null點就返回0(base case);

    需要兩個function,因為getDepth function 返回的都是depth,不是diameter,所以需要diameterOfBinaryTree 來單獨返回diameter;

    每一個點的最大直徑等於左邊的depth 加上 右邊的depth,取所有點中最大的值。

 1 /**
 2  * Definition for a binary tree node.
3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution 11 { 12 int diameter = 0; 13 14 public int diameterOfBinaryTree(TreeNode root) 15 { 16 getDepth(root); 17 18 return diameter; 19 } 20 21 public int getDepth(TreeNode root) 22 { 23 if(root == null) 24 return 0; 25 26 int left = getDepth(root.left); 27 int right = getDepth(root.right); 28 29 int temp = left + right; 30 31 if(temp > diameter) 32 diameter = temp; 33 34 return Math.max(left, right) + 1; 35 } 36 }

參考資料:

http://blog.csdn.net/zhouziyu2011/article/details/64123326

改動了一下,因為temp = left + right + 2 有點繞。返回0更直接易懂。

LeetCode 543. Diameter of Binary Tree (二叉樹的直徑)