All Possible Full Binary Trees 所有可能的完整二叉树

完整二叉树是一类二叉树,其中每个结点恰好有 0 或 2 个子结点。

返回包含 N 个结点的所有可能完整二叉树的列表。 答案的每个元素都是一个可能树的根结点。

答案中每个树的每个结点必须有 node.val=0

你可以按任何顺序返回树的最终列表。

示例:

输入:7
输出:[[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]]
解释:

提示:

  • 1 <= N <= 20

思路:这道题是典型的递归,而且给的数字一定是奇数,那么每次从递归中取出左子树的树集合left,递归取出右子树的集合right,搭配每一个left和right,形成一个新的树,放到一个新的集合中,返回即可。

参考代码:

/**
 * 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*> allPossibleFBTCore(int N, unordered_map<int, vector<TreeNode*>> &hash) {
	if (N < 1) return { nullptr };
	if (N == 1) return { new TreeNode(0) };
	vector<TreeNode*> res;
	TreeNode* root;
	for (int i = 1; i < (N - 1);) {
		vector<TreeNode*> left;
		vector<TreeNode*> right;
		if (hash.find(i) != hash.end()) left = hash[i];
		else {
			left=allPossibleFBTCore(i, hash);
			hash[i] = left;
		}
		if (hash.find(N - 1 - i) != hash.end()) right = hash[N - 1 - i];
		else {
			right=allPossibleFBTCore(N - 1 - i, hash);
			hash[N - 1 - i] = right;
		}
		for (auto l : left) {
			for (auto r : right) {
				root = new TreeNode(0);
				root->left = l;
				root->right = r;
				res.push_back(root);
			}
		}
		i = i + 2;
	}
    hash[N]=res;
	return res;
}
vector<TreeNode*> allPossibleFBT(int N) {
	unordered_map<int, vector<TreeNode*>> hash;
	return allPossibleFBTCore(N, hash);
}
};

猜你喜欢

转载自blog.csdn.net/qq_26410101/article/details/82722282