难度:中等

    题目描述:
    给定一个二叉树,返回它的后序 遍历。
    image.png
    示例:

    1. 输入: [1,null,2,3]
    2. 1
    3. \
    4. 2
    5. /
    6. 3
    7. 输出: [3,2,1]

    解题思路:
    递归法:

    1. var inorderTraversal = function(root) {
    2. let result = [];
    3. const pushRoot = (root) => {
    4. if (root !== null) {
    5. if (root.left !== null) {
    6. pushRoot(root.left);
    7. }
    8. if (root.right !== null) {
    9. pushRoot(root.right);
    10. }
    11. result.push(root.val);
    12. }
    13. };
    14. pushRoot(root);
    15. return result;
    16. };

    迭代法:

    1. const postorderTraversal = (root) => {
    2. const list = [];
    3. const stack = [];
    4. // 当根节点不为空的时候,将根节点入栈
    5. if(root) stack.push(root)
    6. while(stack.length > 0) {
    7. const node = stack.pop()
    8. // 根左右=>右左根
    9. list.unshift(node.val)
    10. // 先进栈左子树后右子树
    11. // 出栈的顺序就变更为先右后左
    12. // 右先头插法入list
    13. // 左再头插法入list
    14. // 实现右左根=>左右根
    15. if(node.left !== null) {
    16. stack.push(node.left)
    17. }
    18. if(node.right !== null) {
    19. stack.push(node.right)
    20. }
    21. }
    22. return list
    23. }