Skip to content

Commit

Permalink
Added the first Tree question
Browse files Browse the repository at this point in the history
  • Loading branch information
b-izad committed Jun 28, 2023
1 parent 75b35c6 commit 66d5711
Showing 1 changed file with 58 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
'''Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 3
Example 2:
Input: root = [1,null,2]
Output: 2
'''
'''DFS and recursive way: '''

# 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:
def maxDepth(self, root: TreeNode) -> int:
if root is None: # base case
return 0
else:
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height) + 1


# BFS iterative way
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def maxDepth(self, root: TreeNode) -> int:
if not root:
return 0

queue = [(root, 1)]
while queue:
node, level = queue.pop(0)
if node.left:
queue.append((node.left, level + 1))
if node.right:
queue.append((node.right, level + 1))

return level

0 comments on commit 66d5711

Please sign in to comment.