Ruka
1 min readApr 30, 2020

[LeetCode][python3]Day30. Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree (30-Day LeetCoding Challenge)

30 days! Lets go Lets go!
N2I -2020.04.30

  1. My solution
class Solution:
def isValidSequence(self, root: TreeNode, arr: List[int]) -> bool:
if not root and arr:
return False
buffer1=[root]
buffer2=[]
f=lambda x:x.val if x else None
for item in arr[:-1]:
buffer2=[x for x in buffer1 if f(x)==item]
if not buffer2:
return False
buffer1=[]
for x in buffer2:
buffer1.append(x.left)
buffer1.append(x.right)
for x in buffer1:
if x and x.val==arr[-1]:
if x.left==None and x.right==None:
return True
return False

Explanation:

The Solution use two buffer. It checks elements in buffer1 if element.val==target. Then throw their child nodes back to buffer1.

Ruka
Ruka

Written by Ruka

HI I’m Ruka. Now a SWE in Taiwan. Contact via email: nayzi9999@gmail.com

No responses yet