Leetcode 894. All Possible Full Binary Trees (二叉树构建好题)

  1. All Possible Full Binary Trees
    Medium

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

解法1:对数目为n的子树,左右子树总和为n-1,左右子树各递归,数目分别为i和n-1-i,i=1…n-2,leftRes和rightRes就包含了各种可能的左子树和右子树的root。然后leftRes和rightRes的结果两两配对,加上一个root就可以构成一个结果。
注意:为什么i=1…n-2,i能不能为0或n-1呢? 如果i=0,那么leftRes为空,如果i=n-1,那么rightRes为空。这个就不是full binary tree了。而且,TreeNode *root = new TreeNode(0); 也不会被执行到。

/**
 * 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) {
        helper(n);
        return mp[n];
    }
private:
    map<int, vector<TreeNode *> > mp;    
    vector<TreeNode *> helper(int n) {
        //if (n == 0) return {NULL}; //这行可以不要。
        if (mp.find(n) != mp.end()) return mp[n];
        if (n == 1) {
            mp[1] = {new TreeNode(0)};
            return mp[1];
        }
        vector<TreeNode *> res;
        for (int i = 1; i < n - 1; i++) { //可以优化成for (int i = 1; i < n - 1; i += 2) {
            vector<TreeNode *> leftRes = helper(i);
            vector<TreeNode *> RightRes = helper(n - 1 - i);
            for (auto left : leftRes) {
                for (auto right : RightRes) {
                    TreeNode *root = new TreeNode(0);
                    root->left = left;
                    root->right = right;
                    res.push_back(root);
                }
            }
        }
        mp[n] = res;
        return res;
    }
};

注意:
for (int i = 1; i < n - 1; i++)可以优化成
for (int i = 1; i < n - 1; i += 2)
因为各个子树的节点数目都是奇数。

你可能感兴趣的:(leetcode,算法,职场和发展)