题目描述
Given a binary tree, return the postorder traversal of its nodes’ values.

方法思路
Approach1: recursive
class Solution {
//Runtime: 0 ms, faster than 100.00%
//Memory Usage: 36.2 MB, less than 25.53%
List<Integer> res = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if(root == null) return res;
postorderTraversal(root.left);
postorderTraversal(root.right);
res.add(root.val);
return res;
}
}
Approach2:iteratively
class Solution{
//Runtime: 0 ms, faster than 100.00%
//Memory Usage: 36.3 MB, less than 14.74%
public List<Integer> postorderTraversal(TreeNode root) {
LinkedList<Integer> res = new LinkedList<>();
if(root == null) return res;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
res.addFirst(node.val);
if(node.left != null)//判断左右子树是否为null,否则会有空指针异常
stack.push(node.left);
if(node.right != null)
stack.push(node.right);
}
return res;
}
}

本文介绍了一种解决二叉树后序遍历问题的两种方法:递归和迭代。递归方法简洁明了,而迭代方法使用栈来实现,避免了递归的深度限制。两种方法均能有效返回二叉树节点值的后序遍历结果。
320

被折叠的 条评论
为什么被折叠?



