|
| 1 | +# time complexity: O(n) |
| 2 | +# space complexity: O(logn) |
| 3 | +from typing import Optional |
| 4 | + |
| 5 | + |
| 6 | +class TreeNode: |
| 7 | + def __init__(self, val=0, left=None, right=None): |
| 8 | + self.val = val |
| 9 | + self.left = left |
| 10 | + self.right = right |
| 11 | + |
| 12 | + |
| 13 | +class Solution: |
| 14 | + def maxDepth(self, root: Optional[TreeNode]) -> int: |
| 15 | + def longestPath(node: Optional[TreeNode]): |
| 16 | + if not node: |
| 17 | + return 0 |
| 18 | + leftPath = longestPath(node.left) |
| 19 | + rightPath = longestPath(node.right) |
| 20 | + return max(leftPath, rightPath)+1 |
| 21 | + return longestPath(root) |
| 22 | + |
| 23 | + |
| 24 | +# time complexity: O(n) |
| 25 | +# space complexity: O(n) |
| 26 | +class Solution: |
| 27 | + def __init__(self): |
| 28 | + self.nextItem = [] |
| 29 | + self.maxDepth = 0 |
| 30 | + |
| 31 | + def nextMaxDepth(self): |
| 32 | + if not self.nextItem: |
| 33 | + return self.maxDepth |
| 34 | + nextNode, nextLvl = self.nextItem.pop(0) |
| 35 | + nextLvl += 1 |
| 36 | + self.maxDepth = max(self.maxDepth, nextLvl) |
| 37 | + if nextNode.left: |
| 38 | + self.nextItem.append((nextNode.left, nextLvl)) |
| 39 | + if nextNode.right: |
| 40 | + self.nextItem.append((nextNode.right, nextLvl)) |
| 41 | + return self.nextMaxDepth() |
| 42 | + |
| 43 | + def maxDepth(self, root): |
| 44 | + if not root: |
| 45 | + return 0 |
| 46 | + self.nextItem = [] |
| 47 | + self.maxDepth = 0 |
| 48 | + self.nextItem.append((root, 0)) |
| 49 | + return self.nextMaxDepth() |
| 50 | + |
| 51 | +# time complexity: O(n) |
| 52 | +# space complexity: O(n) |
| 53 | +class Solution: |
| 54 | + def maxDepth(self, root: TreeNode) -> int: |
| 55 | + stack = [] |
| 56 | + if root is not None: |
| 57 | + stack.append((1, root)) |
| 58 | + |
| 59 | + depth = 0 |
| 60 | + while stack != []: |
| 61 | + currDepth, root = stack.pop() |
| 62 | + if root is not None: |
| 63 | + depth = max(depth, currDepth) |
| 64 | + stack.append((currDepth + 1, root.left)) |
| 65 | + stack.append((currDepth + 1, root.right)) |
| 66 | + |
| 67 | + return depth |
0 commit comments