-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path144- 二叉树的前序遍历.java
42 lines (35 loc) · 1.1 KB
/
144- 二叉树的前序遍历.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
/*
给定一个二叉树,返回它的 前序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
*/
/**
* Definition for a binary tree node. public class TreeNode { int val; TreeNode
* left; TreeNode right; TreeNode(int x) { val = x; } }
*/
class Solution { //迭代法,“比 94-二叉树的中序遍历” 中给出的迭代法更加简洁直观
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
if (root == null) //因为下面root结点直接进栈,必须检查null
return ans;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode cur = stack.pop(); //迭代更新cur变量
ans.add(cur.val);
if (cur.right != null)
stack.push(cur.right);
if (cur.left != null)
stack.push(cur.left);
//进栈先右后左,出栈先左后右
}
return ans;
}
}