|
| 1 | +// Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root. |
| 2 | + |
| 3 | +// For example: |
| 4 | +// Given a binary tree {1,2,3,4,5}, |
| 5 | +// 1 |
| 6 | +// / \ |
| 7 | +// 2 3 |
| 8 | +// / \ |
| 9 | +// 4 5 |
| 10 | +// return the root of the binary tree [4,5,2,#,#,3,1]. |
| 11 | +// 4 |
| 12 | +// / \ |
| 13 | +// 5 2 |
| 14 | +// / \ |
| 15 | +// 3 1 |
| 16 | +// confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ. |
| 17 | + |
| 18 | +// Hide Company Tags LinkedIn |
| 19 | +// Hide Tags Tree |
| 20 | +// Show Similar Problems |
| 21 | + |
| 22 | + |
| 23 | + |
| 24 | +/** |
| 25 | + * Definition for a binary tree node. |
| 26 | + * function TreeNode(val) { |
| 27 | + * this.val = val; |
| 28 | + * this.left = this.right = null; |
| 29 | + * } |
| 30 | + */ |
| 31 | +/** |
| 32 | + * @param {TreeNode} root |
| 33 | + * @return {TreeNode} |
| 34 | + */ |
| 35 | +var upsideDownBinaryTree = function(root) { |
| 36 | + var newRoot = root; |
| 37 | + |
| 38 | + generateUpsideDownHelper(root); |
| 39 | + |
| 40 | + function generateUpsideDownHelper(root) { |
| 41 | + if(!root) { |
| 42 | + return root; |
| 43 | + } |
| 44 | + |
| 45 | + if(!root.left && !root.right) { |
| 46 | + newRoot = root; |
| 47 | + return root; |
| 48 | + } |
| 49 | + |
| 50 | + if(root.left) { |
| 51 | + var ret = generateUpsideDownHelper(root.left); |
| 52 | + ret.left = root.right; |
| 53 | + ret.right = root; |
| 54 | + root.left = null; |
| 55 | + root.right = null; |
| 56 | + } |
| 57 | + |
| 58 | + return root; |
| 59 | + } |
| 60 | + return newRoot; |
| 61 | +}; |
| 62 | + |
| 63 | + |
| 64 | +// simpler solution |
| 65 | +var upsideDownBinaryTree = function(root) { |
| 66 | + // second condition ensure the left most child will be the new root |
| 67 | + if (!root || (!root.left && !root.right)) { |
| 68 | + return root; |
| 69 | + } |
| 70 | + |
| 71 | + let newRoot = upsideDownBinaryTree(root.left); |
| 72 | + console.log(newRoot.val, root.left) |
| 73 | + |
| 74 | + root.left.left = root.right; |
| 75 | + root.left.right = root; |
| 76 | + |
| 77 | + // cannot work if we sub root.left with newRoot |
| 78 | + // since new root is always the left most child |
| 79 | + // [doesn't work] newRoot.left = root.right; |
| 80 | + // [doesn't work] newRoot.right = root; |
| 81 | + |
| 82 | + root.left = null; |
| 83 | + root.right = null; |
| 84 | + |
| 85 | + return newRoot; |
| 86 | +}; |
0 commit comments