maximum-depth-of-bt py3

This commit is contained in:
2022-04-25 11:30:32 +05:30
parent e793d395bd
commit 713154644b
5 changed files with 68 additions and 0 deletions

View File

@@ -0,0 +1,27 @@
# Time: O(N)
# Space: O(N)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
maxDepthValue = 0
def maxDepth(self, root: Optional[TreeNode]) -> int:
'''
Recursive DFS pre-order but storing max globally
'''
def findMax(node, depth):
if node is None: return None
currDepth = depth + 1
self.maxDepthValue = max(currDepth, self.maxDepthValue)
findMax(node.left, currDepth)
findMax(node.right, currDepth)
findMax(root, 0)
return self.maxDepthValue

View File

@@ -0,0 +1,17 @@
# Time: O(N)
# Space: O(N)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
maxDepthValue = 0
def maxDepth(self, root: Optional[TreeNode]) -> int:
'''
Recursive DFS
'''
return 0 if root is None else 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))