543.二叉树的直径,简单易懂0ms

alonwang

关注

阅读 30

2022-01-16

和T124,T687都是一种题

class Solution {
    int max = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        if(root == null) return 0;
        dfs(root);
        return max;
    }

    public int dfs(TreeNode root){
        if(root.left == null && root.right == null) return 0;
        int left = root.left == null ? 0 : dfs(root.left) + 1;
        int right = root.right == null ? 0 : dfs(root.right) + 1;
        max = Math.max(max, left + right);
        return Math.max(left, right);
    }
}~~~

精彩评论(0)

0 0 举报