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

894. All Possible Full Binary Trees

时间:2018-11-19 21:37:58      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:分享图片   情况   where   tput   xpl   应该   output   int   amazon   

一、题目描述

 

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 1:

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:
技术分享图片

 大致意思:

根据输入的节点求最多能生成几个不相同的完全二叉树,将每个二叉树的根节点放在一个vector中返回。

二、解题思路:

首先求所有的完全二叉树首先需要清除完全二叉树的性质:

节点个数为奇数个

所有的节点要么是叶节点要么是度为2节点。

每个二叉树的左右子树也是完全二叉树,我们可以利用枚举思想枚举所有的左右子树的构造情况然后拼接,在求所有左右子树构造情况

时就成了与原问题相同的问题。

数据结构:

对于每一层递归用一个ans 数组来存在本层的所有情况。

代码如下:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     vector<TreeNode*> allPossibleFBT(int N) {
13         //枚举所有可能的左右子数将其根节点返回,对于左子树,右子树的构造同时也是一种递归的过程。
14         //首先题目要求根据节点数目输出相应的树的根节点,与节点顺序无关。
15         if(N==0)
16         {
17             return {};
18         }
19         if(N==1)
20         {
21             return {new TreeNode(0)};//返回值应该为vector 数据类型
22         }
23           vector<TreeNode*> ans;//ans 存放这一层递归可以构成的树情况。
24         for(int i=1;i<N;i+=2)
25         {
26             for(auto l: allPossibleFBT(i))//遍历所有左右子树的情况需要一个二重循环嵌套。
27             {
28                 for(auto r: allPossibleFBT(N-i-1))
29                 {
30                     auto root= new TreeNode(0);
31                     root->left=l;
32                     root->right=r;
33                     ans.push_back(root);
34                     
35                 }
36             }
37         }
38         return ans;
39     }
40 };

三、题目总结

在读本题没有正确get 到题目的点在哪里,导致一直没有思路。

894. All Possible Full Binary Trees

标签:分享图片   情况   where   tput   xpl   应该   output   int   amazon   

原文地址:https://www.cnblogs.com/zydxx/p/9985435.html

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