递归版本

    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. const res = [];
    15. const inOrder = (root) => {
    16. if(!root) return [];
    17. inOrder(root.left);
    18. res.push(root.val);
    19. inOrder(root.right);
    20. }
    21. inOrder(root)
    22. return res
    23. };

    非递归版本

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