LeetCode 894: All Possible Full Binary Trees Solution

Master LeetCode problem 894 (All Possible Full Binary Trees), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

894. All Possible Full Binary Trees

Problem Explanation

Explanation

To generate all possible full binary trees with n nodes where each node has a value of 0, we can use a recursive approach. We can iterate over all possible combinations of left and right subtrees for each node. In each recursive call, we divide the remaining nodes between the left and right subtrees. If there are no remaining nodes, we return a list containing a single node with value 0. We then combine all possible combinations of left and right subtrees to form full binary trees with n nodes.

Time complexity: O(2^n)
Space complexity: O(2^n)

Solution Code

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

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 894 (All Possible Full Binary Trees)?

This page provides optimized solutions for LeetCode problem 894 (All Possible Full Binary Trees) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 894 (All Possible Full Binary Trees)?

The time complexity for LeetCode 894 (All Possible Full Binary Trees) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 894 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 894 in Java, C++, or Python.

Back to LeetCode Solutions