题目
链接:https://leetcode-cn.com/problems/binary-tree-postorder-traversal
给定一个二叉树,返回它的 后序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [3,2,1]
递归
class Solution {
List<Integer> ans = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
traversal(root);
return ans;
}
private void traversal(TreeNode node) {
if (node == null)
return;
traversal(node.left);
traversal(node.right);
ans.add(node.val);
}
}
迭代
class Solution {
List<Integer> ans = new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if (root == null) return ans;
LinkedList<TreeNode> stack = new LinkedList<>();
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 cur = stack.pop();
ans.add(cur.val);
}
}
return ans;
}
}