题目描述
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;
}
}