Binary Tree Inorder Traversal -Left → Root → Right
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]
Explanation:
Example 2:
Input: root = [1,2,3,4,5,null,8,null,null,6,7,9]
Output: [4,2,6,5,7,1,3,9,8]
Explanation:
Example 3:
Input: root = []
Output: []
Example 4:
Input: root = [1]
Output: [1]
Approach 1: Recursive (Briefly)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
inorder(root, result);
return result;
}
void inorder(TreeNode node,List<Integer> result) {
if (node == null) return;
inorder(node.left,result); // 1. Traverse Left
// System.out.print(node.val); // 2. Visit Root
result.add(node.val);
inorder(node.right,result); // 3. Traverse Right
}
}
Approach 2: Iterative (Important)
🔹 Why use a stack?
-
Because we need to go all the way left, and then come back to visit, and go right.
-
The stack remembers the path back up the tree.
🔹 Step-by-Step Algorithm:
-
Initialize an empty
stack
. -
Initialize
current = root
. -
While
current
is not null or stack is not empty:-
Go as far left as possible:
-
Push current to stack
-
Move current to left child
-
-
Once
current
is null:-
Pop top node from stack
-
Visit (add to result)
-
Move to right child
-
-
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while (current != null || !stack.isEmpty()) {
// Step 1: Reach the leftmost node
while (current != null) {
stack.push(current); // Save node
current = current.left; // Move to left
}
// Step 2: Process node
current = stack.pop(); // Go back up
result.add(current.val); // Visit root
// Step 3: Visit right child
current = current.right;
}
return result;
}
}
Comments
Post a Comment