894. All Possible Full Binary Trees

題目

https://leetcode.com/problems/all-possible-full-binary-trees/

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:

解答

這道題沒想到思路,看了一下答案……

class P894_All_Possible_Full_Binary_Trees {

    Map<Integer, List<TreeNode>> mem = new HashMap<>();

    public List<TreeNode> allPossibleFBT(int N) {

        if (!mem.containsKey(N)) {
            LinkedList<TreeNode> ans = new LinkedList<>();
            if (N == 1) {
                TreeNode root = new TreeNode(0);
                ans.add(root);
            } else if (N % 2 == 1) { // 必須是奇數個節點才能形成完全二叉樹
                for (int x = 0; x < N; x++) {
                    int y = N - 1 - x;
                    for (TreeNode left: allPossibleFBT(x)) {
                        for (TreeNode right: allPossibleFBT(y)) {
                            TreeNode root = new TreeNode(0);
                            root.left = left;
                            root.right = right;
                            ans.add(root);
                        }
                    }
                }
            }
            mem.put(N, ans);
        }

        return mem.get(N);

    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章