Find Bottom Left Tree Value LeetCode solution in Python

1
# Definition for a binary tree node.
2
# class TreeNode:
3
# def __init__(self, val=0, left=None, right=None):
4
# self.val = val
5
# self.left = left
6
# self.right = right
7
class Solution:
8
def findBottomLeftValue(self, root: Optional[TreeNode]) -> int:
9

10
res = root.val
11
stack = [(0, root)]
12
prev_d = 0
13

14
while stack:
15

16
curr_d, curr_v = stack.pop(0)
17

18
if curr_v.left:
19
stack.append((curr_d + 1, curr_v.left))
20
if prev_d != curr_d + 1:
21
res = curr_v.left.val
22
prev_d = curr_d + 1
23

24
if curr_v.right:
25
stack.append((curr_d + 1, curr_v.right))
26
if prev_d != curr_d + 1:
27
res = curr_v.right.val
28
prev_d = curr_d + 1
29

30
return res
31

32

33
# An Upvote will be encouraging

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0