Skip to content

Instantly share code, notes, and snippets.

@voxqhuy
Created July 12, 2020 03:41
Show Gist options
  • Save voxqhuy/bd04a3e3f4b012ba0abeee19d3239c00 to your computer and use it in GitHub Desktop.
Save voxqhuy/bd04a3e3f4b012ba0abeee19d3239c00 to your computer and use it in GitHub Desktop.
// 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