码迷,mamicode.com
首页 > 其他好文 > 详细

894. All Possible Full Binary Trees

时间:2018-10-04 17:24:00      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:val   for   二叉树   new   int   span   roo   turn   treenode   

列出所有可能的完全二叉树

/**
 * 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) {
        if(N%2==0)
            return {};
        int n=(N+1)/2;
        vector<TreeNode*> ans;
        if(n==1){
            ans.push_back(new TreeNode(0));
            return ans;
        }
        for(int i=1;i<=n-1;++i){
            vector<TreeNode*>  left=allPossibleFBT(2*i-1);
            vector<TreeNode*> right=allPossibleFBT(2*(n-i)-1);
            for(auto& l : left){
                for(auto& r: right){
                    TreeNode* root=new TreeNode(0);
                    root->left=l;
                    root->right=r;
                    ans.push_back(root);
                }
            }
        }
        return ans;
    }
};

 

894. All Possible Full Binary Trees

标签:val   for   二叉树   new   int   span   roo   turn   treenode   

原文地址:https://www.cnblogs.com/learning-c/p/9742503.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!