remember to add self before each method and variable
Divide and conquer is all u need.
classSolution(object):defpreorderTraversal(self,root):""" :type root: TreeNode :rtype: List[int] """ rst = [] stack = [] if root: # we checked inside the loop for not appending None in the stack, but dont forget checking it at the begining.
stack.append(root)else:return rstwhile(stack): top = stack.pop() rst.append(top.val)if top.right: stack.append(top.right)if top.left: stack.append(top.left)return rst
When solving it in iterative way with stack, remember to append nodes in inverse order, appending later node (right) first (before left).
we checked not appending None in the stack inside the loop, but don't forget also checking it at the beginning.