给你一棵二叉树的根节点 root ,返回其节点值的 后序遍历 。

    示例 1:
    image.png
    输入:root = [1,null,2,3]
    输出:[3,2,1]
    示例 2:

    输入:root = []
    输出:[]
    示例 3:

    输入:root = [1]
    输出:[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 res = []
    15. // const traver = (root) => {
    16. // if (!root) return res
    17. // traver(root.left);
    18. // traver(root.right);
    19. // res.push(root.val);
    20. // return res
    21. // }
    22. // return traver(root)
    23. let stack = [], res = [];
    24. if (root) stack.push(root);
    25. while (stack.length) {
    26. let node = stack.pop();
    27. if (!node) {
    28. res.push(stack.pop().val);
    29. continue;
    30. }
    31. stack.push(node);
    32. stack.push(null);
    33. if (node.right) stack.push(node.right);
    34. if (node.left) stack.push(node.left);
    35. }
    36. return res
    37. };