145. 二叉树的后序遍历
145. Binary Tree Postorder Traversal
题目描述
给定一个二叉树,返回它的 后序 遍历。
LeetCode145. Binary Tree Postorder Traversal
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
Java 实现
Iterative Solution
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> result = new LinkedList<>();
Stack<TreeNode> stack = new Stack<>();
if (root == null) {
return result;
}
stack.push(root);
while (!stack.isEmpty()) {
TreeNode cur = stack.pop();
result.add(0, cur.val);
if (cur.left != null) {
stack.push(cur.left);
}
if (cur.right != null) {
stack.push(cur.right);
}
}
return result;
}
}
Recursive Solution
import java.util.LinkedList;
import java.util.List;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
class Solution {
List<Integer> result = new LinkedList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if (root == null) {
return result;
}
postorderTraversal(root.left);
postorderTraversal(root.right);
result.add(root.val);
return result;
}
}
相似题目
参考资料