题目链接
- https://leetcode.cn/problems/binary-tree-postorder-traversal/
题目描述
给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。
示例 1:

输入:root = [1,null,2,3]
输出:[3,2,1]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
提示:
- 树中节点的数目在范围
[0, 100]内 -100 <= Node.val <= 100
进阶:递归算法很简单,你可以通过迭代算法完成吗?
解题思路
递归法
迭代法
- 前序遍历是中左右,后序遍历是左右中,那么我们只需要调整一下前序遍历的代码,将其变成中右左的遍历顺序,然后再反转
ans数组,输出的结果顺序就是左右中了
AC代码
递归法
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
postorder(root, ans);
return ans;
}
static void postorder(TreeNode root, List<Integer> ans) {
if (root == null) {
return;
}
postorder(root.left, ans);
postorder(root.right, ans);
ans.add(root.val);
}
}
迭代法
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> ans = new ArrayList<>();
if (root == null) {
return ans;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
ans.add(node.val);
if (node.left != null) {
stack.push(node.left);
}
if (node.right != null) {
stack.push(node.right);
}
}
Collections.reverse(ans);
return ans;
}
}
最后
以上就是爱笑花生最近收集整理的关于LeetCode_145_二叉树的后序遍历的全部内容,更多相关LeetCode_145_二叉树内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复