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
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.
問題描述
給定二叉樹, 計算出它的直徑的長度。二叉樹的直徑為樹中任意兩個節點的最長路徑的長度。這個路徑可能通過, 也可能不通過根節點。
問題分析
假設一條路徑通過某個節點, 那麼該路徑的長度為該節點左右子樹的高度之和
於是 ,我們通過後序遍歷, 在獲取每個節點左右子樹高度之和的同時, 計算出通過該節點的路徑長度, 找出最大的路徑長度即可
通過如上分析, 發現處理方法只比求高度多了一步操作, 即找出每個節點對應的路徑長度, 將其當前最長路徑長度比較
解法
class Solution {
private int diameter = Integer.MIN_VALUE;
public int diameterOfBinaryTree(TreeNode root) {
if (root == null) return 0;
depthOfTree(root);
return diameter;
}
public int depthOfTree(TreeNode root) {
if (root == null) return 0;
//後續遍歷求出左右子樹的高度
int l = depthOfTree(root.left);
int r = depthOfTree(root.right);
//求出最長路徑的長度
diameter = Math.max(diameter, l + r);
//返回該節點的高度
return 1 + Math.max(l, r);
}
}
相關文章
- Traversals of binary tree
- Leetcode Binary Tree PathsLeetCode
- [LintCode] Binary Tree Level Order
- 545. Boundary of Binary Tree
- 257. Binary Tree Paths
- Construct String from Binary TreeStruct
- [LintCode] Check Full Binary Tree
- 257-Binary Tree Paths
- 563-Binary Tree Tilt
- 655-Print Binary Tree
- 654-Maximum Binary Tree
- 814-Binary Tree Pruning
- 110-Balanced Binary Tree
- 226-Invert Binary Tree
- 104. Maximum Depth of Binary Tree
- LeetCode 543. Diameter of Binary TreeLeetCode
- Binary Tree Level Order Traversal [LEETCODE]LeetCode
- LeetCode545.Boundary-of-Binary-TreeLeetCode
- Leetcode 226. Invert Binary TreeLeetCode
- [leetcode]binary-tree-inorder-traversalLeetCode
- [leetcode]maximum-depth-of-binary-treeLeetCode
- 662. Maximum Width of Binary Tree
- 173. Binary Search Tree Iterator
- [LeetCode] 226. Invert Binary TreeLeetCode
- [LeetCode] 543. Diameter of Binary TreeLeetCode
- LeetCode之Univalued Binary Tree(Kotlin)LeetCodeKotlin
- LeetCode之Binary Tree Pruning(Kotlin)LeetCodeKotlin
- 111-Minimum Depth of Binary Tree
- 662-Maximum Width of Binary Tree
- Binary-tree-level-order-traversal
- 104-Maximum Depth of Binary Tree
- 637-Average of Levels in Binary Tree
- 669-Trim a Binary Search Tree
- LeetCode#110.Balanced Binary Tree(Tree/Height/DFS/Recursion)LeetCode
- LeetCode 104. Maximum Depth of Binary TreeLeetCode
- LeetCode 98. Validate Binary Search TreeLeetCode
- LeetCode | 144. Binary Tree Preorder TraversalLeetCode
- LeetCode | 145. Binary Tree Postorder TraversalLeetCode