欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

894. All Possible Full Binary Trees

程序员文章站 2022-04-25 10:40:35
...

Problem

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

Return a list of all possible full binary trees with N nodes. Each element of the answer is the root node of one possible tree.

Each node of each tree in the answer must have node.val = 0.

You may return the final list of trees in any order.

Example

Input: 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]]
Explanation:

894. All Possible Full Binary Trees

Solution

满二叉树的节点数一定是奇数。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<TreeNode*> allPossibleFBT(int N) {
        vector<TreeNode*> fbtVec;
        if(N == 0 || N%2==0)
            return fbtVec;
        if(N == 1)
        {
            TreeNode * root = new TreeNode(0);
            fbtVec.push_back(root);
            return fbtVec;
        }
        
        for(int i = 1;i<N;i+=2)
        {
            
            vector<TreeNode *> lRet= allPossibleFBT(i);
            vector<TreeNode *> rRet= allPossibleFBT(N-1-i);

            for(int j = 0;j<lRet.size();++j)
            {   
                for(int k = 0;k<rRet.size();++k)
                {
                	//root不能放在最外层循环去new
                    TreeNode * root = new TreeNode(0);
                    root->left  = lRet[j];
                    root->right = rRet[k];
                    fbtVec.push_back(root);
                }
            }
            
        }

        return fbtVec;
    
    }
    
};