给你一个整数 n
,请你找出所有可能含 n
个节点的 真二叉树 ,并以列表形式返回。答案中每棵树的每个节点都必须符合 Node.val == 0
。
答案的每个元素都是一棵真二叉树的根节点。你可以按 任意顺序 返回最终的真二叉树列表。
真二叉树 是一类二叉树,树中每个节点恰好有 0
或 2
个子节点。
示例 1:
输入:n = 7 输出:[[0,0,0,null,null,0,0,null,null,0,0],[0,0,0,null,null,0,0,0,0],[0,0,0,0,0,0,0],[0,0,0,0,0,null,null,null,null,0,0],[0,0,0,0,0,null,null,0,0]]
示例 2:
输入:n = 3 输出:[[0,0,0]]
提示:
1 <= n <= 20
问题简要描述:返回所有真二叉树
Java
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {List<TreeNode>[] f; public List<TreeNode> allPossibleFBT(int n) {f = new List[n + 1];return dfs(n);}List<TreeNode> dfs(int n) {if (f[n] != null) {return f[n];}if (n == 1) {return List.of(new TreeNode());}List<TreeNode> ans = new ArrayList<>();for (int i = 0; i < n - 1; i++) {int j = n - 1 - i;for (TreeNode left : dfs(i)) {for (TreeNode right : dfs(j)) {ans.add(new TreeNode(0, left, right));}}}return f[n] = ans;}
}
Python3
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:def allPossibleFBT(self, n: int) -> List[Optional[TreeNode]]:@cachedef dfs(n: int) -> List[Optional[TreeNode]]:if n == 1:return [TreeNode()]ans = []for i in range(n - 1):j = n - 1 - ifor left in dfs(i):for right in dfs(j):ans.append(TreeNode(0, left, right))return ansreturn dfs(n)
TypeScript
/*** Definition for a binary tree node.* class TreeNode {* val: number* left: TreeNode | null* right: TreeNode | null* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {* this.val = (val===undefined ? 0 : val)* this.left = (left===undefined ? null : left)* this.right = (right===undefined ? null : right)* }* }*/function allPossibleFBT(n: number): Array<TreeNode | null> {const f: Array<Array<TreeNode | null>> = Array.from({length: n + 1}, () => []);const dfs = (n: number): Array<TreeNode | null> => {if (f[n].length) {return f[n];}if (n == 1) {f[n].push(new TreeNode(0));return f[n];}const ans: Array<TreeNode | null> = [];for (let i = 0; i < n - 1; i++) {let j = n - 1 - i;for (const left of dfs(i)) {for (const right of dfs(j)) {ans.push(new TreeNode(0, left, right));}}}return (f[n] = ans);}return dfs(n);
};