Returning list inside of list (not desired)
I keep returning a list inside of a list for the following LeetCode Problem 257. Binary Tree Paths, which is not what the problem wants. I always seem to run into this issue while solving traversal problems.
Here is my current solution along with it's output.
# 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 binaryTreePaths(self, root: TreeNode, val: str="") -> List[str]:
if not root:
return ""
val += str(root.val) + "->"
if not root.left and not root.right:
return val[:-2]
return [path for path in [self.binaryTreePaths(root.left, val), self.binaryTreePaths(root.right, val)] if path]
Input: [1,2,3,null,5]
Output: [["1->2->5"],"1->3"]
Expected: ["1->2->5","1->3"]
Things I've tried
- Creating a res variable and using res.extend()
res = []
res.extend(path for path in [self.binaryTreePaths(root.left, val), self.binaryTreePaths(root.right, val)] if path)
- Using append instead of extend along with conditionals to try and filter out unwanted elements.
I constantly run into this problem while solving traversal problems so if anyone here has a solution along with some general advice on how to develop an intuition on what's going wrong here and how to solve it in the future, I'd be extremely grateful for your help.
Edit
Well I kept working at trying to fix my solution and after about ~20 minutes, I came up with the following abomination.
class Solution:
def binaryTreePaths(self, root: TreeNode, val: str="") -> List[str]:
if not root:
return ""
val += str(root.val) + "->"
if not root.left and not root.right:
return val[:-2]
r1 = self.binaryTreePaths(root.left, val)
r2 = self.binaryTreePaths(root.right, val)
if isinstance(r1, str):
r1 = [r1]
if isinstance(r2, str):
r2 = [r2]
for i in r1:
if i == "":
r1.pop(r1.index(i))
for i in r2:
if i == "":
r2.pop(r2.index(i))
return r1 + r2
I'm by no means satisfied with my solution as is so if you know of a cleaner fix please continue to post your fix/advice.