6/22/2017 - 6:12 AM

## 94. Binary Tree Inorder Traversal

1. Binary Tree Inorder 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 inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None:
return []
stack = []
res = []
p = root
while p != None or len(stack) != 0:
# First append all the left nodes,
# if there's no left nodes to append,
# consume p and append right nodes.
if p != None:
stack.append(p)
p = p.left
else:
if len(stack)>0:
p = stack[-1]
del stack[-1]
res.append(p.val)
p = p.right
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 inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root == None:
return []
stack = []
res = []
p = root
while p != None or len(stack) != 0:
# don't see curNode.left,
while p != None:
stack.append(p)
p = p.left
curNode = stack[-1]
del stack[-1]
res.append(curNode.val)
p = curNode.right
return res``````

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

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

For example: Given binary tree `[1,null,2,3]`,

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

return `[1,3,2]`.

Note: Recursive solution is trivial, could you do it iteratively?