|
| 1 | +// https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ |
| 2 | +/** |
| 3 | + * 114. Flatten Binary Tree to Linked List |
| 4 | + * Definition for a binary tree node. |
| 5 | + * function TreeNode(val, left, right) { |
| 6 | + * this.val = (val===undefined ? 0 : val) |
| 7 | + * this.left = (left===undefined ? null : left) |
| 8 | + * this.right = (right===undefined ? null : right) |
| 9 | + * } |
| 10 | + */ |
| 11 | +/** |
| 12 | + * @param {TreeNode} root |
| 13 | + * @return {void} Do not return anything, modify root in-place instead. |
| 14 | + */ |
| 15 | +var flatten = function (root) { |
| 16 | + while (root) { |
| 17 | + if (!root.left) { |
| 18 | + root = root.right; |
| 19 | + continue; |
| 20 | + } |
| 21 | + let pre = root.left; |
| 22 | + while (pre.right) { |
| 23 | + pre = pre.right; |
| 24 | + } |
| 25 | + pre.right = root.right; |
| 26 | + root.right = root.left; |
| 27 | + root.left = null; |
| 28 | + root = root.right; |
| 29 | + } |
| 30 | +}; |
| 31 | + |
| 32 | +var flatten = function (root) { |
| 33 | + if (!root) { |
| 34 | + return root; |
| 35 | + } |
| 36 | + const stack = []; |
| 37 | + |
| 38 | + while (root.left || root.right || stack.length) { |
| 39 | + if (root.right) { |
| 40 | + stack.push(root.right); |
| 41 | + } |
| 42 | + if (root.left) { |
| 43 | + root.right = root.left; |
| 44 | + root.left = null; |
| 45 | + } else { |
| 46 | + root.right = stack.pop(); |
| 47 | + } |
| 48 | + root = root.right; |
| 49 | + } |
| 50 | +}; |
0 commit comments