Swift recursive solution


  • 0
    S
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     public var val: Int
     *     public var left: TreeNode?
     *     public var right: TreeNode?
     *     public init(_ val: Int) {
     *         self.val = val
     *         self.left = nil
     *         self.right = nil
     *     }
     * }
     */
    class Solution {
        func maxDepth(_ root: TreeNode?) -> Int {
            
            var sumLeft = 0
            var sumRight = 0
            
            if let root = root {
                
                sumLeft = 1
                sumRight = 1
            
                if let left = root.left {
                    sumLeft = 1 + maxDepth(left)
                } 
                if let right = root.right {
                    sumRight = 1 + maxDepth(right)
                }
            }
            
            return max(sumLeft, sumRight)
        }
    }
    

Log in to reply
 

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