I'm trying to solve trivial binary tree preorder traversal problem from LeetCode. Here is my solution:
# 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 preorderTraversal(self, root: TreeNode, node_list = []) -> List[int]:
if not root:
return []
node_list.append(root.val)
for leaf in (root.left, root.right):
if leaf is not None:
self.preorderTraversal(leaf, node_list)
return node_list
but it don't pass following testcase:
Input: [1]
Output: [1,2,3,1]
Expected: [1]
How can it be possible to get output [1,2,3,1]
from one single node which has no leafs at all. For me, it should add value of the first node (1
) to the values list, iteratively check children-nodes (both of them should be None
) and return node-values list, (which consist of the only not-None value from the first node - [1]
). From where it gets 2,3,1 values if the tree consists form one single node: val = 1, left = None, right = None
?
I am definitely missing something obvious, but cannot figure out what exactly. Please help me out.