|
| 1 | +// Problem: https://leetcode.com/problems/binary-tree-inorder-traversal/ |
| 2 | +// Doc: https://leetcode.com/problems/binary-tree-inorder-traversal/solutions/5505544/inorder-traversal-of-binary-tree-iterative-approach/ |
| 3 | +class TreeNode { |
| 4 | + val: number; |
| 5 | + left: TreeNode | null; |
| 6 | + right: TreeNode | null; |
| 7 | + constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) { |
| 8 | + this.val = val === undefined ? 0 : val; |
| 9 | + this.left = left === undefined ? null : left; |
| 10 | + this.right = right === undefined ? null : right; |
| 11 | + } |
| 12 | +} |
| 13 | + |
| 14 | +function inorderTraversal(root: TreeNode | null): number[] { |
| 15 | + if (!root) return []; |
| 16 | + const stack: TreeNode[] = []; |
| 17 | + const result: number[] = []; |
| 18 | + |
| 19 | + while (stack.length > 0 || root) { |
| 20 | + while (root) { |
| 21 | + stack.push(root); |
| 22 | + root = root.left; |
| 23 | + } |
| 24 | + |
| 25 | + const popped = stack.pop(); |
| 26 | + if (!popped) break; |
| 27 | + result.push(popped.val); |
| 28 | + root = popped.right; |
| 29 | + } |
| 30 | + |
| 31 | + return result; |
| 32 | +} |
| 33 | + |
| 34 | +describe('Binary Tree Inorder Traversal', () => { |
| 35 | + it('#1 should return [1, 3, 2]', () => { |
| 36 | + const root = new TreeNode(1, null, new TreeNode(2, new TreeNode(3))); |
| 37 | + expect(inorderTraversal(root)).toStrictEqual([1, 3, 2]); |
| 38 | + }); |
| 39 | + |
| 40 | + it('#2 should return []', () => { |
| 41 | + expect(inorderTraversal(null)).toStrictEqual([]); |
| 42 | + }); |
| 43 | + |
| 44 | + it('#3 should return [1]', () => { |
| 45 | + const root = new TreeNode(1); |
| 46 | + expect(inorderTraversal(root)).toStrictEqual([1]); |
| 47 | + }); |
| 48 | + |
| 49 | + it('#4 should return [1, 2]', () => { |
| 50 | + const root = new TreeNode(1, null, new TreeNode(2)); |
| 51 | + expect(inorderTraversal(root)).toStrictEqual([1, 2]); |
| 52 | + }); |
| 53 | + |
| 54 | + it('#5 should return [2, 3, 1]', () => { |
| 55 | + const root = new TreeNode(1, new TreeNode(3, new TreeNode(2)), null); |
| 56 | + expect(inorderTraversal(root)).toStrictEqual([2, 3, 1]); |
| 57 | + }); |
| 58 | + |
| 59 | + it('#6 should return [2, 4, 1, 5, 3]', () => { |
| 60 | + const root = new TreeNode( |
| 61 | + 1, |
| 62 | + new TreeNode(2, null, new TreeNode(4)), |
| 63 | + new TreeNode(3, new TreeNode(5)) |
| 64 | + ); |
| 65 | + expect(inorderTraversal(root)).toStrictEqual([2, 4, 1, 5, 3]); |
| 66 | + }); |
| 67 | +}); |
0 commit comments