[LeetCode] 145. Binary Tree Postorder Traversal

Given the root of a binary tree, return the postorder traversal of its nodes’ values.

Example 1:
Example 1
Input: root = [1,null,2,3]
Output: [3,2,1]

Example 2:
Input: root = []
Output: []

Example 3:
Input: root = [1]
Output: [1]

Constraints:
The number of the nodes in the tree is in the range [0, 100].
-100 <= Node.val <= 100

Follow up: Recursive solution is trivial, could you do it iteratively?

给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。

思路

依然是迭代和递归两种做法,两种做法的时间复杂度均是O(n),空间复杂度均是O(h)。
递归没什么好讲的,直接上代码。还是用这个更完整的例子参考。

Tree Traversal

复杂度

时间O(n)
空间O(h)

代码

迭代

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
/**
* 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) {
List<Integer> res = new LinkedList<>();
if (root == null) {
return res;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode cur = stack.pop();
res.addFirst(cur.val);
if (cur.left != null) {
stack.push(cur.left);
}
if (cur.right != null) {
stack.push(cur.right);
}
}
return res;
}
}

递归

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
/**
* 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) {
List<Integer> res = new ArrayList<>();
if (root == null) {
return res;
}
helper(res, root);
return res;
}

private static void helper(List<Integer> res, TreeNode root) {
if (root == null) {
return;
}
helper(res, root.left);
helper(res, root.right);
res.add(root.val);
}
}

[LeetCode] 145. Binary Tree Postorder Traversal
https://shurui91.github.io/posts/1579637700.html
Author
Aaron Liu
Posted on
January 10, 2020
Licensed under