-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInorderBST.java
63 lines (55 loc) · 1.62 KB
/
InorderBST.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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* Binary Tree Inorder Traversal
*
* Given a binary tree, return the inorder traversal of its nodes' values
*
* e.g. IN: [15, 10, 22, 4, 12, 18, 24], OUT: [4, 10, 12, 15, 18, 22, 24]
*
* 15
* / \
* 10 22
* / \ / \
* 4 12 18 24
*
* Complexity: O(n) time and space
*
* Depth First Search(DFS) traversal pathways (Inorder, Preorder, and Postorder).
*
* Inorder strategy: Left -> Root -> Right
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
class InorderBST {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
public List<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> output = new ArrayList<>();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
output.add(curr.val);
curr = curr.right;
}
return output;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(15);
root.left = new TreeNode(10);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(12);
root.right = new TreeNode(22);
root.right.left = new TreeNode(18);
root.right.right = new TreeNode(24);
System.out.println("Inorder: " + new InorderBST().inorderTraversal(root));
}
}