Given the root of a binary tree, return the inorder traversal of its values: left subtree โ node โ right subtree. Follow-up: do it iteratively instead of recursively.
root = [1,null,2,3][1,3,2]root = [1,2,3,4,5,null,8,null,null,6,7,9][4,2,6,5,7,1,3,9,8]1,null,2,3 ยท up to 15 nodescurr isn't null: push it ๐ and go leftRecursive inorder is go(left); visit(node); go(right). The stack stores exactly the nodes whose go(left) call is still running. Each node is pushed once and popped once, so the whole traversal is O(n). Bonus: on a BST, inorder gives the values in sorted order, which is behind "Validate BST" (98) and "Kth Smallest" (230).
Empty tree โ [] (the loop never runs). Left-skewed tree โ stack grows to n, so worst-case space is O(n). Loop condition must be curr != null || !stack.isEmpty(): either one alone stops too early. Morris traversal gets O(1) extra space by temporarily threading right pointers.