-
Notifications
You must be signed in to change notification settings - Fork 0
/
145- 二叉树的后序遍历.java
47 lines (39 loc) · 1.11 KB
/
145- 二叉树的后序遍历.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
46
47
/*
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution { // 官方给出的迭代法,作弊式的逆向前序遍历
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> ans = new LinkedList<>(); //注意最前面类型是LinkedList而不是List
if (root == null) // 因为下面root结点直接进栈,必须检查null
return ans;
LinkedList<TreeNode> stack = new LinkedList<>();
stack.add(root);
while (!stack.isEmpty()) {
TreeNode cur = stack.pollLast();
ans.addFirst(cur.val);
if (cur.left != null)
stack.add(cur.left);
if (cur.right != null)
stack.add(cur.right);
}
return ans;
}
}