-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patha_144.java
More file actions
29 lines (27 loc) · 769 Bytes
/
a_144.java
File metadata and controls
29 lines (27 loc) · 769 Bytes
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
package datastructure.tree;
import java.util.*;
/**
* 非递归实现二叉树的前序遍历
*/
public class a_144 {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ret = new ArrayList<>();
if(root == null) return ret;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
if (node == null) continue;
ret.add(node.val);
if (node.right != null) stack.push(node.right);
if (node.left != null) stack.push(node.left);
}
return ret;
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
}