描述

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

示例 1:

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

输出: [3,2,1]


题解

递归法:

  1. /**
  2. * Definition for a binary tree node.
  3. * function TreeNode(val, left, right) {
  4. * this.val = (val===undefined ? 0 : val)
  5. * this.left = (left===undefined ? null : left)
  6. * this.right = (right===undefined ? null : right)
  7. * }
  8. */
  9. /**
  10. * @param {TreeNode} root
  11. * @return {number[]}
  12. */
  13. var postorderTraversal = function(root) {
  14. let list = []
  15. postorder(root, list)
  16. return list
  17. };
  18. const postorder = (root, list) => {
  19. if (!root) return null
  20. postorder(root.left, list)
  21. postorder(root.right, list)
  22. list.push(root.val)
  23. return list
  24. }