/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    private int maxValue = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        getDia(root);
        return maxValue - 1;
    }
    
    private int getDia(TreeNode root) {
        if (root == null) {
            return 0;
        }
        
        int left = getDia(root.left);
        int right = getDia(root.right);
        maxValue = Math.max(left + right + 1, maxValue);
        return Math.max(left, right) + 1;
    }
}

 

posted on 2017-09-03 07:29  keepshuatishuati  阅读(71)  评论(0编辑  收藏  举报