Simple Java Recursive Solution


  • 0
    private int maxDiameter = 0;
    public int diameterOfBinaryTree(TreeNode root) {
        if(root==null) return 0;
        maxDepth(root);
        return this.maxDiameter;
    }
    public int maxDepth(TreeNode root) {
        int leftDepth = root.left==null ? 0 : maxDepth(root.left)+1;
        int rightDepth = root.right==null ? 0 : maxDepth(root.right)+1;
        this.maxDiameter = Math.max(this.maxDiameter, leftDepth+rightDepth);
        return Math.max(leftDepth,rightDepth);
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.