-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
58 changes: 58 additions & 0 deletions
58
Twopointer/Binary search/Linked List/Trees/104. Maximum Depth of Binary Tree.py
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
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 | ||
|