Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes’ values.
Example
Input: [1,null,2,3]
Output: [1,3,2]
Solution
# recursively
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
def traversal(root, res):
if root:
traversal(root.left, res)
res.append(root.val)
traversal(root.right, res)
res = []
traversal(root, res)
return res
# iteratively
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