Skip to content

Commit d3f8acd

Browse files
committed
solve 94: binary tree inorder traversal using iteration
1 parent 7f92527 commit d3f8acd

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import java.util.ArrayList;
2+
3+
/*
4+
* @lc app=leetcode id=94 lang=java
5+
*
6+
* [94] Binary Tree Inorder Traversal
7+
*
8+
* https://leetcode.com/problems/binary-tree-inorder-traversal/description/
9+
*
10+
* algorithms
11+
* Medium (55.10%)
12+
* Total Accepted: 426.4K
13+
* Total Submissions: 767.5K
14+
* Testcase Example: '[1,null,2,3]'
15+
*
16+
* Given a binary tree, return the inorder traversal of its nodes' values.
17+
*
18+
* Example:
19+
*
20+
*
21+
* Input: [1,null,2,3]
22+
* ⁠ 1
23+
* ⁠ \
24+
* ⁠ 2
25+
* ⁠ /
26+
* ⁠ 3
27+
*
28+
* Output: [1,3,2]
29+
*
30+
* Follow up: Recursive solution is trivial, could you do it iteratively?
31+
*
32+
*/
33+
/**
34+
* Definition for a binary tree node.
35+
* public class TreeNode {
36+
* int val;
37+
* TreeNode left;
38+
* TreeNode right;
39+
* TreeNode(int x) { val = x; }
40+
* }
41+
*/
42+
class Solution {
43+
public List<Integer> inorderTraversal(TreeNode root) {
44+
List<Integer> list = new ArrayList<>();
45+
Stack<TreeNode> stack = new Stack<>();
46+
TreeNode p = root;
47+
48+
while (!stack.empty() || p != null) {
49+
while (p != null) {
50+
stack.push(p);
51+
p = p.left;
52+
}
53+
if (!stack.empty()) {
54+
p = stack.pop();
55+
list.add(p.val);
56+
p = p.right;
57+
}
58+
}
59+
60+
return list;
61+
}
62+
}
63+

0 commit comments

Comments
 (0)