# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def preorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
s = [] # use as a stack
res = [] # stores result
if (root == None):
return res
else:
s.append(root)
while(s):
# if s is empty, s is False. not s is True
curr = s.pop()
res.append(curr.val)
if(curr.right != None):
s.append(curr.right) # pre-order print left first, so push right first
if(curr.left != None):
s.append(curr.left)
return res
Before append, make sure a node is not None.
Be the first to comment
You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.