forked from y-ncao/Python-Study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary_Tree_Inorder_Traversal.py
53 lines (46 loc) · 1.31 KB
/
Binary_Tree_Inorder_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 inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].
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 inorderTraversal(self, root):
return self.inorderTraversal_1(root)
def inorderTraversal_1(self, root):
stack = []
current = root
res = []
while current is not None or len(stack) > 0:
if current is not None:
stack.append(current)
current = current.left
elif len(stack) > 0:
current = stack.pop()
res.append(current.val)
current = current.right
return res
def inorderTraversal_2(self, root):
res = []
self.inorderTraversal_rec(root, res)
return res
def inorderTraversal_rec(self, root, res):
if root is None:
return
self.inorderTraversal_rec(root.left, res)
res.append(root.val)
self.inorderTraversal_rec(root.right, res)