894. All Possible Full Binary Trees

Medium (Trung bình) C++ 🔗 Xem trên LeetCode

📋 Đề Bài

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

🧠 Thuật Toán & Kỹ Thuật

Tree Traversal (Duyệt cây)
⏱️ Thời gian O(n²)
💾 Không gian O(n)

💻 Lời Giải

C++ 0894-all-possible-full-binary-trees.cpp
/**
 * 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) {
        if (n == 1) {
            return {new TreeNode(0)};
        }
        vector<TreeNode*> res;
        
        for (int i = 2; i < n; i += 2) {
            vector<TreeNode*> all_way_node_left = allPossibleFBT(i - 1);
            vector<TreeNode*> all_way_node_right = allPossibleFBT(n - i);
            
            for (TreeNode* node_left : all_way_node_left) {
                for (TreeNode* node_right : all_way_node_right) {
                    TreeNode *root = new TreeNode(0, node_left, node_right);
                    res.push_back(root);
                }
            }
        }
        
        return res;
    }
};