1. 程式人生 > >LeetCode-All Possible Full Binary Trees

LeetCode-All Possible Full Binary Trees

一、Description

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.

題目大意:

給定一個數N,找出所有結點數為N的滿數。滿樹指的是每個結點的子節點數要麼為0要麼為2。

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:


二、Analyzation

首先,對於N為偶數,不可能存在一個滿足條件的滿樹,因此N必須為奇數。除開根結點,一棵滿樹可以分解為有i(i為奇數)個結點的左子樹和n-i-1(n-i-1為奇數)個結點的右子樹,所以只需遍歷i的取值。


三、Accepted code

class Solution {
    public List<TreeNode> allPossibleFBT(int N) {
        List<TreeNode> list = new ArrayList<>();
        if (N % 2 == 0 || N <= 0) {
            return list;
        }
        if (N == 1) {
            list.add(new TreeNode(0));
            return list;
        }
        for (int i = 1; i < N; i += 2) {
            List<TreeNode> left = allPossibleFBT(i);
            List<TreeNode> right = allPossibleFBT(N - i - 1);
            for (TreeNode l : left) {
                for (TreeNode r : right) {
                    TreeNode node = new TreeNode(0);
                    node.left = l;
                    node.right = r;
                    list.add(node);
                }
            }
        }
        return list;
    }
}