-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathT7.java
More file actions
50 lines (40 loc) · 1.19 KB
/
T7.java
File metadata and controls
50 lines (40 loc) · 1.19 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
47
48
49
50
package testCode;
import java.util.ArrayList;
import java.util.Stack;
public class T7 {
public static final void main(String args[]) {
ArrayList<Integer> result = new ArrayList<>();
result.add(null);
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
System.out.print(preorderTraversal(root).size());
}
public static ArrayList<Integer> preorderTraversal(TreeNode root) {
if (null == root) {
return new ArrayList<Integer>();
}
ArrayList<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
TreeNode currentNode;
while (0 != stack.size()) {
currentNode = stack.pop();
result.add(currentNode.val);
if (null != currentNode.right) {
stack.push(currentNode.right);
}
if (null != currentNode.left) {
stack.push(currentNode.left);
}
}
return result;
}
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}