题目说明
给定一个二叉树,返回它的 后序 遍历。
- 进阶: 递归算法很简单,你可以通过迭代算法完成吗?
示例
示例 1:
1 2 3 4 5 6 7 8
| 输入: [1,null,2,3] 1 \ 2 / 3
输出: [3,2,1]
|
笔者理解
此题是一道二叉树算法问题,在力扣题库中被定义为简单题。
解法
当笔者阅读完此题后,采用了迭代的办法,迭代就是通过栈来模拟递归的过程,让我们来看看具体如何实现的吧。
实现
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
|
class Solution {
public List<Integer> postorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); Deque<TreeNode> stack = new LinkedList<>();
if (root != null) { stack.push(root); }
while (!stack.isEmpty()) { TreeNode node = stack.pop(); if (node != null) { stack.push(node); stack.push(null); if (node.right != null) { stack.push(node.right); } if (node.left != null) { stack.push(node.left); } } else { TreeNode temp = stack.pop(); result.add(temp.val); } } return result; } }
|
时间和空间效率还行,可见此解法还比较适合此题。

总结
本题是今天的一题,难度是为简单,感兴趣的朋友都可以去尝试一下,此题还有其他更多的解法,朋友们可以自己逐一尝试。