给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。

    示例 1:
    image.png
    输入:root = [1,null,2,3]
    输出:[1,3,2]
    示例 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 inorderTraversal = function (root) {
    14. // 递归法==========================
    15. // let res = []
    16. // const traver = (root) => {
    17. // if (!root) { return res };
    18. // traver(root.left);
    19. // res.push(root.val)
    20. // traver(root.right)
    21. // return res
    22. // }
    23. // return traver(root)
    24. // 迭代法===========================
    25. // 入栈 左 -> 右
    26. // 出栈 左 -> 中 -> 右
    27. // let stack = [], res = [];
    28. // let cur = root;
    29. // while (stack.length || cur) {
    30. // if (cur) {
    31. // stack.push(cur);
    32. // // 左
    33. // cur = cur.left;
    34. // } else {
    35. // // --> 弹出 中
    36. // cur = stack.pop();
    37. // res.push(cur.val);
    38. // cur = cur.right
    39. // }
    40. // }
    41. // return res
    42. // 终极版==============================
    43. const stack = [], res = [];
    44. if (root) { stack.push(root) }
    45. while (stack.length) {
    46. const node = stack.pop();
    47. if (!node) {
    48. res.push(stack.pop().val);
    49. continue;
    50. }
    51. if (node.right) stack.push(node.right);
    52. stack.push(node);
    53. // 占位标识符
    54. stack.push(null);
    55. if (node.left) stack.push(node.left);
    56. }
    57. return res;
    58. };