-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeInorderTraversal.java
More file actions
46 lines (39 loc) · 1.29 KB
/
BinaryTreeInorderTraversal.java
File metadata and controls
46 lines (39 loc) · 1.29 KB
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
39
40
41
42
43
44
45
46
package solutions;
import datastructure.TreeNode;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
// [Problem] https://leetcode.com/problems/binary-tree-inorder-traversal/
class BinaryTreeInorderTraversal {
// Recursion
// O(n) time, O(logn) space
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> values = new ArrayList<>();
addValueInorder(root, values);
return values;
}
private void addValueInorder(TreeNode node, List<Integer> values) {
if (node != null) {
addValueInorder(node.left, values);
values.add(node.val);
addValueInorder(node.right, values);
}
}
// Stack
// O(n) time, O(n) space
public List<Integer> inorderTraversalStack(TreeNode root) {
List<Integer> values = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode currentNode = root;
while (currentNode != null || !stack.isEmpty()) {
while (currentNode != null) {
stack.push(currentNode);
currentNode = currentNode.left;
}
currentNode = stack.pop();
values.add(currentNode.val);
currentNode = currentNode.right;
}
return values;
}
}