-
Notifications
You must be signed in to change notification settings - Fork 8
/
Main.java
68 lines (54 loc) · 1.61 KB
/
Main.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
64
65
66
67
68
import java.util.Stack;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
/*
The binary tree in this example is shown as follow
1
/ \
2 3
/ \ /
4 5 6
/
7
pre-order traversal: 1 2 4 5 7 3 6
*/
public class Main {
public static void preorderTraversalByRecursion(TreeNode root) {
if (root == null) return;
System.out.print(root.val + " ");
preorderTraversalByRecursion(root.left);
preorderTraversalByRecursion(root.right);
}
public static void preorderTraversal(TreeNode root) {
Stack<TreeNode> nodeStack = new Stack<>();
while (root != null || !nodeStack.empty()) {
while (root != null) {
System.out.print(root.val + " ");
nodeStack.push(root.right);
root = root.left;
}
root = nodeStack.pop();
}
}
public static TreeNode generateBTree(Integer[] nodes, int index) {
TreeNode node = null;
if (index < nodes.length && nodes[index] != null) {
node = new TreeNode(nodes[index]);
node.left = generateBTree(nodes, index * 2 + 1);
node.right = generateBTree(nodes, index * 2 + 2);
}
return node;
}
public static void main(String[] args) {
Integer[] nodes = {1, 2, 3, 4, 5, 6, null, null, null, 7};
TreeNode root = generateBTree(nodes, 0);
preorderTraversalByRecursion(root);
System.out.println();
preorderTraversal(root);
System.out.println();
}
}