Created
July 12, 2020 03:41
-
-
Save voxqhuy/bd04a3e3f4b012ba0abeee19d3239c00 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://leetcode.com/problems/maximum-depth-of-binary-tree/ | |
// Recursive | |
// Time: O(n), Space: O(n) | |
func maxDepth(_ root: TreeNode?) -> Int { | |
guard let root = root else { return 0 } | |
return 1 + max(maxDepth(root.left), maxDepth(root.right)) | |
} | |
// Iterative | |
// Time: O(n), Space: O(n) | |
func maxDepth(_ root: TreeNode?) -> Int { | |
guard let root = root else { return 0 } | |
var stack = [(TreeNode, Int)]() | |
stack.append((root, 1)) | |
var maxDepth = 0 | |
while !stack.isEmpty { | |
let (node, depth) = stack.popLast()! | |
maxDepth = max(depth, maxDepth) | |
if let left = node.left { stack.append((left, depth + 1)) } | |
if let right = node.right { stack.append((right, depth + 1)) } | |
} | |
return maxDepth | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment