104. Maximum Depth of Binary Tree--LeetCode Record

Tong_hdj發表於2016-07-08

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

/**
 * 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 {

        if root == nil {
            return 0
        }

        var leftCount:Int = maxDepth(root?.left)
        var rightCount:Int = maxDepth(root?.right)

        return leftCount > rightCount ? leftCount + 1 : rightCount + 1

    }
}

相關文章