-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBinaryTreeInorderTraversal.java
38 lines (34 loc) · 1.04 KB
/
BinaryTreeInorderTraversal.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
import definitions.TreeNode;
public class BinaryTreeInorderTraversal {
private List<Integer> list = new ArrayList<>();
// Iterative Approach
public List<Integer> inorderTraversal(TreeNode root) {
if (root == null)
return list;
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while (!stack.isEmpty() || current != null) {
if (current != null) {
stack.push(current);
current = current.left;
} else {
current = stack.pop();
list.add(current.val);
current = current.right;
}
}
return list;
}
// Recursive Approach
public List<Integer> inorderTraversalRecursive(TreeNode root) {
if (root == null)
return list;
inorderTraversalRecursive(root.left);
list.add(root.val);
inorderTraversalRecursive(root.right);
return list;
}
}