All Possible Full Binary Trees Problem


Description

LeetCode Problem 894.

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:

1
2
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:

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

Constraints:

  • 1 <= n <= 20


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
 * 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 {
public:
    vector<TreeNode*> allPossibleFBT(int N) {
        vector<TreeNode*> ans;
        TreeNode* root = new TreeNode(0);
        if (N == 1) {
            ans.push_back(root);
            return ans;
        } else if (N % 2 == 1) {
            for (int x = 0; x < N; x ++) {
                int y = N - x - 1;
                vector<TreeNode*> left_ans = allPossibleFBT(x);
                vector<TreeNode*> right_ans = allPossibleFBT(y);
                for (vector<TreeNode*>::iterator it1 = left_ans.begin(); 
                    it1 != left_ans.end(); it1 ++) {
                    for (vector<TreeNode*>::iterator it2 = right_ans.begin(); 
                        it2 != right_ans.end(); it2 ++) {
                        TreeNode* top = new TreeNode(0);
                        top->left = *it1;
                        top->right = *it2;
                        ans.push_back(top);
                    }
                }
            }
        }
        return ans;
    }
};




Related Posts

Valid Permutations For DI Sequence Problem

LeetCode 903. You are given a string s of length...

Tallest Billboard Problem

LeetCode 956. You are installing a billboard and want it...

Sum Of Subarray Minimums Problem

LeetCode 907. Given an array of integers arr, find the...

Stone Game Problem

LeetCode 877. Alice and Bob play a game with piles...

Split Array With Same Average Problem

LeetCode 805. You are given an integer array nums.

Soup Servings Problem

LeetCode 808. There are two types of soup, type A...