Skip to content

Commit 2d98d78

Browse files
authored
Merge pull request akgmage#1787 from akgmage/dev
Dev
2 parents 83b1271 + 347f2e7 commit 2d98d78

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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+
}

0 commit comments

Comments
 (0)