6/22/2017 - 6:05 AM

## 144. Binary Tree Preorder Traversal

1. Binary Tree Preorder Traversal
``````# 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]
"""
if root == None:
return []
stack = [root]
res = []
while len(stack) != 0:
curNode = stack[-1]
del stack[-1]
res.append(curNode.val)
if curNode.right:
stack.append(curNode.right)
if curNode.left:
stack.append(curNode.left)

return res
``````
``````# 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]
"""
if root == None:
return []
self.res = []
self.dfs(root)
return self.res

def dfs(self, node):
if node == None:
return
self.res.append(node.val)
self.dfs(node.left)
self.dfs(node.right)
``````

https://leetcode.com/problems/binary-tree-preorder-traversal/#/description

Given a binary tree, return the preorder traversal of its nodes' values.

For example: Given binary tree `{1,#,2,3}`,

``````   1
\
2
/
3
``````

return `[1,2,3]`. Note: Recursive solution is trivial, could you do it iteratively?