給定一棵二叉樹,你需要計算它的直徑長度。一棵二叉樹的直徑長度是任意兩個結點路徑長度中的最大值。這條路徑可能穿過根結點。
示例 :
給定二叉樹
? ? ? ? ? 1
? ? ? ? ?/ \
? ? ? ? 2 ? 3
? ? ? ?/ \ ? ??
? ? ? 4 ? 5 ? ?
返回?3, 它的長度是路徑 [4,2,1,3] 或者?[5,2,1,3]。
注意:兩結點之間的路徑長度是以它們之間邊的數目表示。
思路:helper一路求著最大深度,然后更新最大答案(也就是左+右深度+1本身)
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {int ans=1;public int diameterOfBinaryTree(TreeNode root) {helper(root);return ans-1;}public int helper(TreeNode root) {if(root==null)return 0;int left=helper(root.left);int right=helper(root.right);ans=Math.max(ans,left+right+1);return Math.max(left,right)+1;}
}
?