543. Diameter of Binary Tree

2017-10-02  本文已影响0人  namelessEcho

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

猜你喜欢

热点阅读