-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPreOrderTreeObj.java
More file actions
52 lines (47 loc) · 1.1 KB
/
Copy pathPreOrderTreeObj.java
File metadata and controls
52 lines (47 loc) · 1.1 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
51
52
package one_day_test;
import java.util.LinkedList;
import java.util.List;
/**
*
* 144. 二叉树的前序遍历
* 给定一个二叉树,返回它的 前序 遍历。
*
* 示例:
*
* 输入: [1,null,2,3]
* 1
* \
* 2
* /
* 3
*
* 输出: [1,2,3]
* 进阶: 递归算法很简单,你可以通过迭代算法完成吗?
*/
public class PreOrderTreeObj {
public List<Integer> preorderTraversal(TreeNode root) {
LinkedList<TreeNode> stack = new LinkedList<>();
LinkedList<Integer> output = new LinkedList<>();
if (root == null) {
return output;
}
stack.add(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pollLast();
output.add(node.val);
if (node.right != null) {
stack.add(node.right);
}
if (node.left != null) {
stack.add(node.left);
}
}
return output;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
}