File tree Expand file tree Collapse file tree 1 file changed +28
-12
lines changed Expand file tree Collapse file tree 1 file changed +28
-12
lines changed Original file line number Diff line number Diff line change 20
20
*/
21
21
class Solution {
22
22
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 ;
30
38
}
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 ;
34
48
}
35
- return li ;
49
+
50
+ // Return the final in-order traversal result
51
+ return result ;
36
52
}
37
- }
53
+ }
You can’t perform that action at this time.
0 commit comments