94. Binary Tree Inorder Traversal
# Medium, DFS
Solution 1: Recursive
Use help function, return nothing when satisficed stop condition. Pass
resultlist as a parameter. Returnresultin 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;
}
}class Solution {
private void inorder(TreeNode root, ArrayList<Integer> res) {
// stop condition
if(root == null) return;
inorder(root.left, res);
res.add(root.val);
inorder(root.right, res);
}
public ArrayList<Integer> inorderTraversal(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer>();
inorder(root, res);
return res;
}
}Solution 2: Divide & Conquer
Divide and conquer are the same as preorder binary traversal. Combine order is changed to
left-root-right. Returnresultwhen satisfied stop condition.
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
Last updated
Was this helpful?