File tree Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Expand file tree Collapse file tree 1 file changed +53
-0
lines changed Original file line number Diff line number Diff line change
1
+
2
+ /**
3
+ * Given the root of a binary tree, return the inorder traversal of its nodes' values.
4
+ * Definition for a binary tree node.
5
+ * public class TreeNode {
6
+ * int val;
7
+ * TreeNode left;
8
+ * TreeNode right;
9
+ * TreeNode() {}
10
+ * TreeNode(int val) { this.val = val; }
11
+ * TreeNode(int val, TreeNode left, TreeNode right) {
12
+ * this.val = val;
13
+ * this.left = left;
14
+ * this.right = right;
15
+ * }
16
+ * }
17
+ */
18
+ /**
19
+
20
+ */
21
+ class Solution {
22
+ public List <Integer > inorderTraversal (TreeNode root ) {
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 ;
38
+ }
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 ;
48
+ }
49
+
50
+ // Return the final in-order traversal result
51
+ return result ;
52
+ }
53
+ }
You can’t perform that action at this time.
0 commit comments