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.
A 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个节点的所有完全二叉树的结构。每个节点值为0. 完全二叉树是一个二叉树,其所有节点包含0个或2个子节点。
思路:与96. Unique Binary Search Trees类似,采用动态规划方法,将n-1个节点分为左右子节点。采用递归方法分别求出从1到n-2个节点的完全二叉树结构,将其置于根节点的左右子树位置。为减少计算,使用hashmap来保存子树结构。小编使用一个vector
- /**
- * Definition for a binary tree node.
- * struct TreeNode {
- * int val;
- * TreeNode *left;
- * TreeNode *right;
- * TreeNode() : val(0), left(nullptr), right(nullptr) {}
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
- * };
- */
- class Solution {
- private:
- vector
> subTree; - public:
- vector
allPossibleFBT(int n) { - if(subTree.size() > n && subTree[n].size() > 0)
- return subTree[n];
- while(subTree.size() <= n) subTree.push_back({});
- if(n == 1){
- subTree[1].push_back(new TreeNode(0));
- } else {
- for(int i = 1; i < n-1; i+=2){
- vector
left = allPossibleFBT(i); - vector
right = allPossibleFBT(n-i-1); - for(auto l : left){
- for(auto r : right){
- TreeNode* root = new TreeNode(0);
- root->left = l;
- root->right = r;
- subTree[n].push_back(root);
- }
- }
- }
- }
- return subTree[n];
- }
- };