maximum_depth_of_binary_tree

Solution

	
	from publicmatt.leet import TreeNode


def dfs(root: TreeNode) -> int:
    if root is None:
        return 0
    return 1 + max(dfs(root.left), dfs(root.right))


def bfs(root: TreeNode) -> int:
    from collections import deque

    level = 0
    q = deque()
    if root is not None:
        q.append(root)
    while q:
        count = len(q)
        for _ in range(count):
            node = q.popleft()
            if node.left is not None:
                q.append(node.left)
            if node.right is not None:
                q.append(node.right)
        level += 1
    return level

	

Tests

	
	import pytest

from publicmatt.leet import TreeNode
from publicmatt.leet.problems.maximum_depth_of_binary_tree import bfs, dfs


@pytest.fixture()
def simple() -> TreeNode:
    nums = [1, 2, 3, 4, 5]
    root = TreeNode.from_list(nums)
    return root


def test_dfs(simple):
    assert dfs(simple) == 3


def test_bfs(simple):
    assert bfs(simple) == 3

	
maximum_depth_of_binary_tree