From 66d57114a7d955d4827be8169178f54ddca93011 Mon Sep 17 00:00:00 2001 From: Bahareh Date: Tue, 27 Jun 2023 22:57:45 -0400 Subject: [PATCH] Added the first Tree question --- .../104. Maximum Depth of Binary Tree.py | 58 +++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Twopointer/Binary search/Linked List/Trees/104. Maximum Depth of Binary Tree.py diff --git a/Twopointer/Binary search/Linked List/Trees/104. Maximum Depth of Binary Tree.py b/Twopointer/Binary search/Linked List/Trees/104. Maximum Depth of Binary Tree.py new file mode 100644 index 0000000..a313fbb --- /dev/null +++ b/Twopointer/Binary search/Linked List/Trees/104. Maximum Depth of Binary Tree.py @@ -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 +