Implement an iterative, pre-order traversal of a given binary tree, return the list of keys of each node in the tree as it is pre-order traversed.
Examples
5
/ \
3 8
/ \ \
1 4 11
Pre-order traversal is [5, 3, 1, 4, 8, 11]
class Solution(object):
def preOrder(self, root):
if not root:
return []
res = []
self.helper(root,res)
return res
def helper(self,root,res):
if not root:
return
res.append(root.val)
self.helper(root.left,res)
self.helper(root.right,res)
网友评论