-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathSolution144.java
45 lines (37 loc) · 927 Bytes
/
Solution144.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
package algorithm.leetcode;
import java.util.LinkedList;
import java.util.List;
/**
* @author: mayuan
* @desc: 二叉树的前序遍历
* @date: 2019/03/09
*/
public class Solution144 {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new LinkedList<>();
if (null == root) {
return ans;
}
LinkedList<TreeNode> stack = new LinkedList<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode cur = stack.pop();
ans.add(cur.val);
if (null != cur.right) {
stack.push(cur.right);
}
if (null != cur.left) {
stack.push(cur.left);
}
}
return ans;
}
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
}