[LeetCode] 894. All Possible Full Binary Trees

linspiration

Problem

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

clipboard.png

Note:

1 <= N <= 20

Solution

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

                    root.left = l;
                    root.right = r;
                    res.add(root);
                }
            }
        }
        return res;
    }
    
    //If we only need the count
    Map<Integer, Integer> map = new HashMap<>();
    public int allPossibleCount(int N) {
        map.put(1, 1);
        if (N == 1) return 1;
        if (N < 1 || N%2 == 0) return 0;
        int count = 0;
        for (int i = 1; i < N-1; i+=2) {
            int left = map.containsKey(i) ? map.get(i) : allPossibleCount(i);
            int right = map.containsKey(N-1-i) ? map.get(N-1-i) : allPossibleCount(N-1-i);
            map.put(i, left);
            map.put(N-1-i, right);
            count += left * right;
        }
        return count;
    }
}
阅读 1.9k

Road to Glory
對酒當歌,人生幾何?譬如朝露,去日苦多。
161 声望
31 粉丝
0 条评论
161 声望
31 粉丝
宣传栏