-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack145.java
More file actions
58 lines (55 loc) · 1.45 KB
/
Stack145.java
File metadata and controls
58 lines (55 loc) · 1.45 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
53
54
55
56
57
58
package stack;
import utils.TreeNode;
import java.util.ArrayList;
import java.util.List;
/**
* @ProjectName: leetcode
* @Package: stack
* @ClassName: Stack145
* @Author: markey
* @Description:
* 给定一个二叉树,返回它的 后序 遍历。
*
* 示例:
*
* 输入: [1,null,2,3]
* 1
* \
* 2
* /
* 3
*
* 输出: [3,2,1]
* 进阶: 递归算法很简单,你可以通过迭代算法完成吗?
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* @Date: 2020/1/5 10:46
* @Version: 1.0
*/
public class Stack145 {
/**
* Runtime: 0 ms, faster than 100.00% of Java online submissions for Binary Tree Postorder Traversal.
* Memory Usage: 34.8 MB, less than 100.00% of Java online submissions for Binary Tree Postorder Traversal.
* @param root
* @return
*/
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
postorder(res, root);
return res;
}
private void postorder(List<Integer> res, TreeNode root) {
if (root == null) {
return;
}
if (root.left != null) {
postorder(res, root.left);
}
if (root.right != null) {
postorder(res, root.right);
}
res.add(root.val);
}
}