给定一个二叉树,返回它的 后序 遍历。

示例:

输入: [1,null,2,3]
1
\
2
/
3

输出: [3,2,1]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?

递归:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public List<Integer> postorderTraversal(TreeNode root) {
  18. List<Integer> keys = new ArrayList<>();
  19. postorderTraversal(root, keys);
  20. return keys;
  21. }
  22. public static void postorderTraversal(TreeNode root, List<Integer> keys){
  23. if(root == null){
  24. return;
  25. }
  26. //先遍历左子树
  27. postorderTraversal(root.left, keys);
  28. //再遍历右子树
  29. postorderTraversal(root.right, keys);
  30. //遍历根节点
  31. keys.add(root.val);
  32. }
  33. }

迭代:

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode() {}
  8. * TreeNode(int val) { this.val = val; }
  9. * TreeNode(int val, TreeNode left, TreeNode right) {
  10. * this.val = val;
  11. * this.left = left;
  12. * this.right = right;
  13. * }
  14. * }
  15. */
  16. class Solution {
  17. public List<Integer> postorderTraversal(TreeNode root) {
  18. List<Integer> list = new ArrayList<>();
  19. Stack<TreeNode> stack = new Stack<>();
  20. stack.push(root);
  21. //后序遍历:left->right->root 倒过来是root->right->left 则此过程和前序遍历相似
  22. //前序遍历迭代是:root->left->right
  23. while(!stack.isEmpty()){
  24. TreeNode node = stack.pop();
  25. if(node == null){
  26. continue;
  27. }
  28. list.add(node.val);
  29. if(node.left!=null){
  30. stack.push(node.left);
  31. }
  32. if(node.right!=null){
  33. stack.push(node.right);
  34. }
  35. }
  36. Collections.reverse(list);
  37. //正确的结果需要对list进行翻转
  38. return list;
  39. }
  40. }