/** * Definition for a binary tree node. * class TreeNode { * val: number * left: TreeNode | null * right: TreeNode | null * constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } * } */ function inorderTraversal(root: TreeNode | null): number[] { const ans: number[] = []; while (root) { if (!root.left) { ans.push(root.val); root = root.right; } else { let prev = root.left; while (prev.right && prev.right != root) { prev = prev.right; } if (!prev.right) { prev.right = root; root = root.left; } else { ans.push(root.val); prev.right = null; root = root.right; } } } return ans; }