「这是我参与2022首次更文挑战的第22天,活动详情查看:2022首次更文挑战」
题目
给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。
示例 1:

输入:root = [1,null,2,3]
输出:[3,2,1]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
提示:
- 树中节点的数目在范围
[0, 100]内 -100 <= Node.val <= 100
**进阶:**递归算法很简单,你可以通过迭代算法完成吗?
解题
解题一:递归
思路
使用递归方法,返回顺序:左子树、右子树、根
代码
class Solution {
private static void putValue(TreeNode root, ArrayList<Integer> result) {
if (root.left != null) {
putValue(root.left, result);
}
if (root.right != null) {
putValue(root.right, result);
}
result.add(root.val);
}
public List<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
putValue(root, result);
return result;
}
}
总结
- 执行耗时:0 ms,击败了 100.00% 的 Java 用户
- 内存消耗:36.9 MB,击败了 5.39% 的 Java 用户
解题二:栈
思路
使用栈的思想,两个栈(firstStack 和 secondStack)组成一个队列
- 先把头节点放入 firstStack
- 当 firstStack 不为空时
- 弹出 firstStack 的元素 pop 加入 secondStack 中
- 加入 pop 的右孩子,如果有
- 加入 pop 的左孩子,如果有
- 循环执行 2
- 将 secondStack 的元素依次弹出存入 result 中
代码
/**
* Definition for a binary tree node.
*/
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {
}
TreeNode(int val) {
this.val = val;
}
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
ArrayList<Integer> result = new ArrayList<>();
if (root == null) {
return result;
}
Stack<TreeNode> firstStack = new Stack<>();
Stack<TreeNode> secondStack = new Stack<>();
firstStack.push(root);
while (!firstStack.isEmpty()) {
TreeNode pop = firstStack.pop();
secondStack.push(pop);
if (pop.left != null) {
firstStack.push(pop.left);
}
if (pop.right != null) {
firstStack.push(pop.right);
}
}
while(!secondStack.isEmpty()){
result.add(secondStack.pop().val);
}
return result;
}
}
总结
性能分析
- 执行耗时:0 ms,击败了 100.00% 的 Java 用户
- 内存消耗:39.2 MB,击败了 18.11% 的 Java 用户