|
| 1 | +/** |
| 2 | + * 431. Encode N-ary Tree to Binary Tree |
| 3 | + * https://leetcode.com/problems/encode-n-ary-tree-to-binary-tree/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Design an algorithm to encode an N-ary tree into a binary tree and decode the binary tree |
| 7 | + * to get the original N-ary tree. An N-ary tree is a rooted tree in which each node has no |
| 8 | + * more than N children. Similarly, a binary tree is a rooted tree in which each node has no |
| 9 | + * more than 2 children. There is no restriction on how your encode/decode algorithm should |
| 10 | + * work. You just need to ensure that an N-ary tree can be encoded to a binary tree and this |
| 11 | + * binary tree can be decoded to the original N-nary tree structure. |
| 12 | + * |
| 13 | + * Nary-Tree input serialization is represented in their level order traversal, each group |
| 14 | + * of children is separated by the null value (See following example). |
| 15 | + * |
| 16 | + * For example, you may encode the following 3-ary tree to a binary tree in this way: |
| 17 | + * - Input: root = [1,null,3,2,4,null,5,6] |
| 18 | + * |
| 19 | + * Note that the above is just an example which might or might not work. You do not necessarily |
| 20 | + * need to follow this format, so please be creative and come up with different approaches yourself. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * // Definition for a _Node. |
| 25 | + * function _Node(val,children) { |
| 26 | + * this.val = val; |
| 27 | + * this.children = children; |
| 28 | + * }; |
| 29 | + */ |
| 30 | + |
| 31 | +/** |
| 32 | + * Definition for a binary tree node. |
| 33 | + * function TreeNode(val) { |
| 34 | + * this.val = val; |
| 35 | + * this.left = this.right = null; |
| 36 | + * } |
| 37 | + */ |
| 38 | + |
| 39 | +class Codec { |
| 40 | + constructor() {} |
| 41 | + |
| 42 | + encode = function(root) { |
| 43 | + if (!root) return null; |
| 44 | + |
| 45 | + const binaryRoot = new TreeNode(root.val); |
| 46 | + |
| 47 | + if (root.children.length > 0) { |
| 48 | + binaryRoot.left = this.encode(root.children[0]); |
| 49 | + } |
| 50 | + |
| 51 | + let sibling = binaryRoot.left; |
| 52 | + for (let i = 1; i < root.children.length; i++) { |
| 53 | + if (sibling) { |
| 54 | + sibling.right = this.encode(root.children[i]); |
| 55 | + sibling = sibling.right; |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + return binaryRoot; |
| 60 | + }; |
| 61 | + |
| 62 | + decode = function(root) { |
| 63 | + if (!root) return null; |
| 64 | + |
| 65 | + const updated = new _Node(root.val, []); |
| 66 | + let sibling = root.left; |
| 67 | + while (sibling) { |
| 68 | + updated.children.push(this.decode(sibling)); |
| 69 | + sibling = sibling.right; |
| 70 | + } |
| 71 | + |
| 72 | + return updated; |
| 73 | + }; |
| 74 | +} |
0 commit comments