forked from y-ncao/Python-Study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary_Tree_Preorder_Traversal.py
53 lines (46 loc) · 1.32 KB
/
Binary_Tree_Preorder_Traversal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
"""
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?
"""
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @return a list of integers
def preorderTraversal(self, root):
return self.preorderTraversal_1(root)
def preorderTraversal_1(self, root):
stack = []
current = root
res = []
while current is not None or len(stack)>0:
if current is not None:
res.append(current.val)
stack.append(current)
current = current.left
elif len(stack)>0:
current = stack.pop()
current = current.right
return res
def preorderTraversal_2(self, root):
res = []
self.preorderTraversal_rec(root, res)
return res
def preorderTraversal_rec(self, root, res):
if root is None:
return
res.append(root.val)
self.preorderTraversal_rec(root.left, res)
self.preorderTraversal_rec(root.right, res)