Simple Swift Solution


  • 0
    J

    The diameter is either:

    1. The height of left subtree + height of right subtree
    2. The diameter of left subtree or diameter of right subtree

    Take the max of either above.

    class Solution {
        func heightOfBinaryTree(_ root: TreeNode?) -> Int {
            guard let node = root else { return 0 }
            return 1 + max(heightOfBinaryTree(node.left), heightOfBinaryTree(node.right));
        }
        
        func diameterOfBinaryTree(_ root: TreeNode?) -> Int {
            guard let node = root else { return 0 }
            let hl = heightOfBinaryTree(node.left)
            let hr = heightOfBinaryTree(node.right)
            
            return max(hl + hr, max(diameterOfBinaryTree(node.left), diameterOfBinaryTree(node.right)))
        }
    }
    

Log in to reply
 

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