# leetcode 94. Binary Tree Inorder Traversal （python）

### 描述

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

Example 1:

``````Input: root = [1,null,2,3]
Output: [1,3,2]

Example 2:

``````Input: root = []
Output: []

Example 3:

``````Input: root = [1]
Output: [1]

Example 4:

``````Input: root = [1,2]
Output: [2,1]

Example 5:

``````Input: root = [1,null,2]
Output: [1,2]

Note:

``````The number of nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100

### 解答

``````class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
result = []
def dfs(root):
if not root:
return
dfs(root.left)
result.append(root.val)
dfs(root.right)
dfs(root)
return result

### 运行结果

``````Runtime: 20 ms, faster than 54.47% of Python online submissions for Binary Tree Inorder Traversal.
Memory Usage: 13.5 MB, less than 48.15% of Python online submissions for Binary Tree Inorder Traversal.

### 解答

``````class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def inorderTraversal(self, root):
res, stack = [], []
while True:
while root:
stack.append(root)
root = root.left
if not stack:
return res
node = stack.pop()
res.append(node.val)
root = node.right

### 运行结果

``````Runtime: 46 ms, faster than 5.99% of Python online submissions for Binary Tree Inorder Traversal.
Memory Usage: 13.6 MB, less than 19.47% of Python online submissions for Binary Tree Inorder Traversal.