美文网首页
543. Diameter of Binary Tree

543. Diameter of Binary Tree

作者: namelessEcho | 来源:发表于2017-10-02 09:56 被阅读0次

递归,因为不一定在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;
    }
}

相关文章

网友评论

      本文标题: 543. Diameter of Binary Tree

      本文链接:https://www.haomeiwen.com/subject/savzextx.html