Skip to content

Commit 347f2e7

Browse files
committed
add comments
1 parent 9f08f18 commit 347f2e7

File tree

1 file changed

+28
-12
lines changed

1 file changed

+28
-12
lines changed

Trees/Binary Trees/inorder_traversal.java

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,34 @@
2020
*/
2121
class Solution {
2222
public List<Integer> inorderTraversal(TreeNode root) {
23-
List<Integer> li = new ArrayList<>();
24-
Stack<TreeNode> s = new Stack<>();
25-
TreeNode curr = root;
26-
while(curr != null || !s.isEmpty()) {
27-
while(curr != null) {
28-
s.push(curr);
29-
curr = curr.left;
23+
// List to store the in-order traversal result
24+
List<Integer> result = new ArrayList<>();
25+
26+
// Stack to simulate the recursive call stack
27+
Stack<TreeNode> stack = new Stack<>();
28+
29+
// Current node starts from the root
30+
TreeNode current = root;
31+
32+
// Continue traversal until current node is null and stack is empty
33+
while (current != null || !stack.isEmpty()) {
34+
// Traverse all the way to the leftmost node, pushing each node onto the stack
35+
while (current != null) {
36+
stack.push(current);
37+
current = current.left;
3038
}
31-
curr = s.pop();
32-
li.add(curr.val);
33-
curr = curr.right;
39+
40+
// Pop the top node from the stack (current leftmost node)
41+
current = stack.pop();
42+
43+
// Add the value of the current node to the result list
44+
result.add(current.val);
45+
46+
// Move to the right subtree of the current node
47+
current = current.right;
3448
}
35-
return li;
49+
50+
// Return the final in-order traversal result
51+
return result;
3652
}
37-
}
53+
}

0 commit comments

Comments
 (0)