543. Diameter of Binary Tree

Easy
跟之前做过的有一道题很像,也是用height() method写,但是并不是返回height, 只是在求height的过程中更新了需要求的那个变量

/**
 * 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) {
        if (root == null){
            return 0;
        }   
        height(root);
        return max;
    }
    
    private int height(TreeNode root){
        if (root == null){
            return -1;
        }
        int left = height(root.left);
        int right = height(root.right);
        max = Math.max(max, left + right + 2);
        return Math.max(left, right) + 1;
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/27047230f73a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞