|
| 1 | +/** |
| 2 | + * 894. All Possible Full Binary Trees |
| 3 | + * https://leetcode.com/problems/all-possible-full-binary-trees/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given an integer n, return a list of all possible full binary trees with n nodes. Each node |
| 7 | + * of each tree in the answer must have Node.val == 0. |
| 8 | + * |
| 9 | + * Each element of the answer is the root node of one possible tree. You may return the final |
| 10 | + * list of trees in any order. |
| 11 | + * |
| 12 | + * A full binary tree is a binary tree where each node has exactly 0 or 2 children. |
| 13 | + */ |
| 14 | + |
| 15 | +/** |
| 16 | + * Definition for a binary tree node. |
| 17 | + * function TreeNode(val, left, right) { |
| 18 | + * this.val = (val===undefined ? 0 : val) |
| 19 | + * this.left = (left===undefined ? null : left) |
| 20 | + * this.right = (right===undefined ? null : right) |
| 21 | + * } |
| 22 | + */ |
| 23 | +/** |
| 24 | + * @param {number} n |
| 25 | + * @return {TreeNode[]} |
| 26 | + */ |
| 27 | +var allPossibleFBT = function(n) { |
| 28 | + const memo = new Map(); |
| 29 | + return generateTrees(n); |
| 30 | + |
| 31 | + function generateTrees(nodes) { |
| 32 | + if (nodes % 2 === 0) return []; |
| 33 | + if (nodes === 1) return [new TreeNode(0)]; |
| 34 | + if (memo.has(nodes)) return memo.get(nodes); |
| 35 | + |
| 36 | + const result = []; |
| 37 | + for (let leftNodes = 1; leftNodes < nodes - 1; leftNodes += 2) { |
| 38 | + const rightNodes = nodes - 1 - leftNodes; |
| 39 | + const leftTrees = generateTrees(leftNodes); |
| 40 | + const rightTrees = generateTrees(rightNodes); |
| 41 | + |
| 42 | + for (const left of leftTrees) { |
| 43 | + for (const right of rightTrees) { |
| 44 | + result.push(new TreeNode(0, left, right)); |
| 45 | + } |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + memo.set(nodes, result); |
| 50 | + return result; |
| 51 | + } |
| 52 | +}; |
0 commit comments