Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // MARK: - 104. Maximum Depth of Binary Tree
- // 1 вариант
- func maxDepth(_ root: TreeNode?) -> Int {
- if root == nil {
- return 0
- }
- return 1 + max(maxDepth(root?.left), maxDepth(root?.right))
- }
- // 2 вариант
- func maxDepth(_ root: TreeNode?) -> Int {
- if root == nil {
- return 0
- }
- // максимум для второго уровня maximum + 1 = 0 + 1 = 1 - что верно
- var maximum = 0
- func dfs(_ node: TreeNode?, maximum: Int) -> Int {
- if node == nil {
- return maximum
- }
- return max(dfs(node?.left, maximum: maximum+1), dfs(node?.right, maximum: maximum+1))
- }
- return max(dfs(root?.left, maximum: maximum+1), dfs(root?.right, maximum: maximum+1))
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement