題目來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/diameter-of-binary-tree
給定一棵二叉樹,你需要計算它的直徑長度。一棵二叉樹的直徑長度是任意兩個結(jié)點路徑長度中的最大值。這條路徑可能穿過根結(jié)點。
示例 :
給定二叉樹
1
/ \
2 3
/ \
4 5
返回 3, 它的長度是路徑 [4,2,1,3] 或者 [5,2,1,3]。
注意:兩結(jié)點之間的路徑長度是以它們之間邊的數(shù)目表示。
由于本題中的樹節(jié)點數(shù)據(jù)沒有用,所以可以修改原本的值,表示為該節(jié)點最大的直徑。代碼如下:
/**
* 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) {
int[] ans = {0};
setLen(root,ans);
return ans[0];
}
private void setLen(TreeNode root,int[] ans){
if(root == null)
return;
setLen(root.left,ans);
setLen(root.right,ans);
TreeNode left = root.left;
TreeNode right = root.right;
if(left == null && right == null){
root.val = 0;
}else if(left != null && right != null){
root.val = Math.max(left.val,right.val) + 1;
ans[0] = Math.max(ans[0],2+left.val+right.val);
}else if(left == null){
root.val = right.val + 1;
}else{
root.val = left.val + 1;
}
ans[0] = Math.max(ans[0],root.val);
}
}