94. Binary Tree Inorder Traversal
# Medium, DFS
Solution 1: Recursive
Use help function, return nothing when satisficed stop condition. Pass
result
list as a parameter. Returnresult
in main function
// Some code
class Solution {
ArrayList<Integer> res = new ArrayList<Integer>();
public List<Integer> inorderTraversal(TreeNode root) {
if(root == null)
return res;
inorderTraversal(root.left);
res.add(root.val);
inorderTraversal(root.right);
return res;
}
}
Solution 2: Divide & Conquer
Divide and conquer are the same as preorder binary traversal. Combine order is changed to
left-root-right
. Returnresult
when satisfied stop condition.
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
# consider edge case
result = []
if root == None:
return result
# regular case
left = self.inorderTraversal(root.left)
right = self.inorderTraversal(root.right)
result.extend(left)
result.append(root.val)
result.extend(right)
return result
Solution 1 is faster than solution 2.
Solution 3: Iterative (while-loop)
Push all root until left most to the stack, then pop it and add it to res. Switch to the right subtree, then repeat the last steps. It obeys the order left -> root -> right
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def inorderTraversal(self, root: TreeNode) -> List[int]:
stack = []
res = []
# edge case
if root == None:
return res
# regular case
while root != None or len(stack) != 0:
while root != None:
stack.append(root)
root = root.left
root = stack.pop()
res.append(root.val)
root = root.right
return res
Last updated
Was this helpful?