首页 > 其他分享 >[LeetCode] 894. All Possible Full Binary Trees

[LeetCode] 894. All Possible Full Binary Trees

时间:2023-07-23 11:34:03浏览次数:38  
标签:Binary Full TreeNode val right 二叉树 894 null left

Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each tree in the answer must have Node.val == 0.

Each element of the answer is the root node of one possible tree. You may return the final list of trees in any order.

full binary tree is a binary tree where each node has exactly 0 or 2 children.

Example 1:

Input: n = 7
Output: [[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]]

Example 2:

Input: n = 3
Output: [[0,0,0]]

Constraints:

  • 1 <= n <= 20

所有可能的真二叉树。

给你一个整数 n ,请你找出所有可能含 n 个节点的 真二叉树 ,并以列表形式返回。答案中每棵树的每个节点都必须符合 Node.val == 0 。

答案的每个元素都是一棵真二叉树的根节点。你可以按 任意顺序 返回最终的真二叉树列表。

真二叉树 是一类二叉树,树中每个节点恰好有 0 或 2 个子节点。

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/all-possible-full-binary-trees
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路是 dfs + memo,记忆化递归。

注意真二叉树的定义,每个 node 只有 0 个或 2 个子节点,那么对于任意一棵真二叉树而言,他的 node 总个数应该只能为奇数。不过这里我们需要处理一个 corner case,就是当 n == 1 的时候,我们可以得到一棵树,只有一个根节点。对于其他 n > 1 的情况,我们思考一下,此时左子树应该有 i 个节点,i 为奇数;那么右子树应该有 n - 1 - i 个节点。我们需要遍历所有情况,把 i 和 n - 1 - i 的不同组合都找到,并用一个 hashmap 存下来,这样 n 足够大的时候,我们就省去重复计算。

时间O(2^n) - 卡特兰数

空间O(2^n) - 也应该有这么多种结果

Java实现

 1 /**
 2  * Definition for a binary tree node.
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode() {}
 8  *     TreeNode(int val) { this.val = val; }
 9  *     TreeNode(int val, TreeNode left, TreeNode right) {
10  *         this.val = val;
11  *         this.left = left;
12  *         this.right = right;
13  *     }
14  * }
15  */
16 class Solution {
17     Map<Integer, List<TreeNode>> memo = new HashMap();
18 
19     public List<TreeNode> allPossibleFBT(int n) {
20         if (!memo.containsKey(n)) {
21             List<TreeNode> res = new ArrayList<>();
22             // corner case
23             if (n == 1) {
24                 res.add(new TreeNode(0));
25             } else if (n % 2 == 1) {
26                 for (int i = 1; i < n - 1; i += 2) {
27                     int j = n - 1 - i;
28                     for (TreeNode left : allPossibleFBT(i)) {
29                         for (TreeNode right : allPossibleFBT(j)) {
30                             TreeNode root = new TreeNode(0);
31                             root.left = left;
32                             root.right = right;
33                             res.add(root);
34                         }
35                     }
36                 }
37             }
38             memo.put(n, res);
39         }
40         return memo.get(n);
41     }
42 }

 

LeetCode 题目总结

标签:Binary,Full,TreeNode,val,right,二叉树,894,null,left
From: https://www.cnblogs.com/cnoodle/p/17574813.html

相关文章

  • mysql 索引类型 fulltext
    如何实现MySQL索引类型fulltext简介在MySQL中,fulltext是一种特殊的索引类型,它可以提供更高效的全文搜索功能。本文将向你介绍如何使用fulltext索引类型来优化全文搜索的性能。流程图以下是使用fulltext索引类型实现全文搜索的流程图:步骤操作1创建包含ful......
  • 每日算法之四十六:Add Binary(二进制字符创相加)
    二进制字符创相加,通过进位的方式逐位考虑。也可以把相加的过程抽象成一个函数。Giventwobinarystrings,returntheirsum(alsoabinarystring).Forexample,a= "11"b= "1"Return "100".方法一:classSolution{public:stringaddBinary(stringa,string......
  • 【每日一题】Problem 538B. Quasi Binary
    原题解决思路最简单的思路就是贪心了,每次生成不超过目标值的\(quasibinary\),即可使最终数量最少#include<bits/stdc++.h>intquasibinary(intmax){intres=0;intp=0;while(max>0){if(max%10>0){res+=int(pow(10,......
  • 升级EF7连接SQL server出错SqlException: A connection was successfully established
    今天把项目里的Microsoft.EntityFrameworkCore.SqlServer和Microsoft.EntityFrameworkCore.Tools从6.0.6升级到了最新的7.0.9。一运行程序出错了。Win32Exception:证书链是由不受信任的颁发机构颁发的。UnknownlocationSqlException:Aconnectionwassuccessfullyestab......
  • rand.Read() 和 io.ReadFull(rand.Reader) 的区别?
    golang的随机包rand.go中我们可以看到rand.Read其实是调用的io.Reader.Read()1://Packagerandimplementsacryptographicallysecure1://Packagerandimplementsacryptographicallysecure2://pseudorandomnumbergenerator.3:packagerand4:......
  • nf_conntrack: table full, dropping packet
    参考:linux路由跟踪表满错误nf_conntrack:tablefull,droppingpacket原理解决方法说明ping,dmesg或者/var/log/messages日志中这个报错,说明服务器网络方面遇到了瓶颈。此时查看cat/proc/sys/net/netfilter/nf_conntrack_max和cat/proc/sys/net/netfilter/nf_conntra......
  • (2023.7.11)usb: ring buffer full
    现象:在对usb接口的5G模组灌包时出现异常打印,xhci-hcdxhci-hcd.0.auto:ERRORunkown eventtype37/USBGadgetDriver定义了很多traceevent,使用者可以在用户空间通过ftrace接口,追踪USBGadgetDriver的行为;/用户空间接口路径为/sys/kernel/debug/tracing/events/dwc3:包含了......
  • Sum in Binary Tree
    SuminBinaryTreetimelimitpertest1secondmemorylimitpertest256megabytesinputstandardinputoutputstandardoutputVanyareallylikesmath.Onedaywhenhewassolvinganothermathproblem,hecameupwithaninterestingtree.Thistree......
  • CodeForces 997C Sky Full of Stars
    洛谷传送门CF传送门考虑容斥,钦定\(i\)行\(j\)列放同一种颜色,其余任意。\(i=0\)或\(j=0\)的情况平凡,下面只考虑\(i,j\ne0\)的情况。答案为:\[\sum\limits_{i=1}^n\sum\limits_{j=1}^n(-1)^{i+j+1}\binom{n}{i}\binom{n}{j}3^{(n-i)(n-j)+1}......
  • 【构造,树】【Loj】Loj6669 Nauuo and Binary Tree
    2023.7.3ProblemLink交互库有一棵\(n\)个点的二叉树,你每次可以询问两个点之间的距离,猜出这棵二叉树。\(n\le3000\),询问次数上限\(30000\)。首先给你距离一定是先把每个点的深度问出来,确定一个大致的考虑顺序。然后我们开始仔细思考“距离”这个条件怎么用。发现询问两个......