递归,因为不一定在root上是最大的,需要对每个节点进行判断
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max = 0;
public int diameterOfBinaryTree(TreeNode root) {
dia(root);
return max ;
}
private int dia(TreeNode root)
{
if(root==null)return -1;
int left =dia(root.left);
int right=dia(root.right);
int sum=left+right+2;
if(sum>max)
max=sum;
return left>right?left+1:right+1;
}
}
网友评论