https://leetcode.com/problems/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.
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.
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution {
int max = 0;
public int DiameterOfBinaryTree(TreeNode root)
{
MaxDepth(root);
return max;
}
public int MaxDepth(TreeNode root)
{
if (root == null) return 0;
int left = MaxDepth(root.left);
int right = MaxDepth(root.right);
max = Math.Max(max, left + right);
return Math.Max(left, right) + 1;
}
}
Runtime: 88 ms, faster than 99.83%
of C# online submissions.
Memory Usage: 24.8 MB, less than 25.0%
of C# online submissions.
Time Complexity: O(n)
Space Complextiy: O(n)
我們來複習吧!與 tree 有關的文章你必須知道 ↓
[Day 22] 演算法刷題 LeetCode 101. Symmetric Tree (Easy) Part 1 - Recursion
[Day 23] 演算法刷題 LeetCode 101. Symmetric Tree (Easy) Part 2 - Iteration
這題跟昨天的題目非常相似,就是要找出 tree 裡的 最長路徑
要知道什麼找出最長路徑,就要先知道怎麼找出 tree 裡的 最大深度
↓
[Day 24] 演算法刷題 LeetCode 104. Maximum Depth of Binary Tree (Easy)
本來想得很簡單,只要找出 root.left 的 MaxDepth 及 root.right 的 MaxDepth 相加就好,但案情絕對沒有這麼單純!!!!
概念是對的,但應該要改成找出 所有節點的 left MaxDepth 及 所有節點的 right MaxDepth 相加最大值
才對
因為會有這種奇怪情況,最長路徑不經過 root,所以要全部都掃過
MaxDepth
method
遞迴 Recursion
找出 left 節點的最大深度
遞迴 Recursion
找出 right 節點的最大深度
這邊就是在紀錄除了root 外的最長路徑
往下多一階
的意思以上就是這次 LeetCode 刷題的分享啦!
如果其它人有更棒的想法及意見,請留言或寄信(t4730@yahoo.com.tw) 給我。
那我們就下回見囉