Skip to content

Commit 9f08f18

Browse files
committed
add inorder traversal using stack
1 parent 61a8cbe commit 9f08f18

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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<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;
30+
}
31+
curr = s.pop();
32+
li.add(curr.val);
33+
curr = curr.right;
34+
}
35+
return li;
36+
}
37+
}

0 commit comments

Comments
 (0)