Given the root of a binary tree, return the inorder traversal of its nodes’ values.

    Example 1:
    94. Binary Tree Inorder Traversal - 图1Input: root = [1,null,2,3] Output: [1,3,2]
    Example 2:
    Input: root = [] Output: []
    Example 3:
    Input: root = [1] Output: [1]
    Example 4:
    94. Binary Tree Inorder Traversal - 图2Input: root = [1,2] Output: [2,1]
    Example 5:
    94. Binary Tree Inorder Traversal - 图3Input: root = [1,null,2] Output: [1,2]

    Constraints:

    • The number of nodes in the tree is in the range [0, 100].
    • -100 <= Node.val <= 100

    Follow up: Recursive solution is trivial, could you do it iteratively?

    Runtime: 68 ms, faster than 96.16% of JavaScript online submissions for Binary Tree Inorder Traversal.
    Memory Usage: 38.7 MB, less than 55.06% of JavaScript online submissions for Binary Tree Inorder Traversal.

    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. let node = root;
    15. const stack = [];
    16. const result = [];
    17. while(node || stack.length > 0) {
    18. while(node) {
    19. stack.push(node);
    20. node = node.left;
    21. }
    22. if (stack.length > 0) {
    23. node = stack.pop();
    24. result.push(node.val);
    25. node = node.right;
    26. }
    27. }
    28. return result;
    29. };