94. Binary Tree Inorder Traversal
Stack, Tree, DFS, Binary Tree ·Problem Statement
link: https://leetcode.com/problems/binary-tree-inorder-traversal/ https://leetcode.cn/problems/binary-tree-inorder-traversal/
Given the root of a binary tree, return the inorder traversal of its nodes’ values.
Example:
Input: root = [1,null,2,3]
Output: [1,3,2]
Input: root = []
Output: []
Input: root = [1]
Output: [1]
Solution Approach
recursion
Algorithm
- Initialization: Create an empty list res for the result.
- Recursive Traversal: Use the inorder function to visit the left child, current node, and then the right child.
- Execution: If the root exists, begin the traversal with the inorder function and return the res list.
Implement
class Solution:
def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
res = []
def inorder(node):
if node.left:
inorder(node.left)
res.append(node.val)
if node.right:
inorder(node.right)
if root:
inorder(root)
return res