forked from sammorozov/1337Code_tasks
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path104. Maximum Depth of Binary Tree23.py
42 lines (34 loc) · 1.12 KB
/
104. Maximum Depth of Binary Tree23.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# 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: Optional[TreeNode]) -> int:
# n = 0
# node = root
# number = 0
# depths = []
# def bst(node, number, depths):
# if node.left:
# node = node.left
# number += 1
# elif node.right:
# node = node.right
# number += 1
# else:
# depths.append(number)
# return bst(node, number, depths)
# bst(root, 0, depths)
# return max(depths)
from typing import *
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
def bst(node, depth):
if not node:
return depth
left_depth = bst(node.left, depth + 1)
right_depth = bst(node.right, depth + 1)
return max(left_depth, right_depth)
return bst(root, 0)