题目
Given a binary tree, return the inorder traversal of its nodes’ values.
Have you met this question in a real interview?
Yes
Example
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,3,2].
Challenge
Can you do it without recursion?
思路
非递归。
代码
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param: root: A Tree
@return: Inorder in ArrayList which contains node values.
"""
def inorderTraversal(self, root):
# write your code here
res_list = []
stack = []
while root or stack:
while root:
stack.append(root)
root = root.left
if stack:
root = stack[-1]
stack.pop(-1)
res_list.append(root.val)
root = root.right
return res_list