Home [Medium] All Possible Full Binary Trees
Post
Cancel

[Medium] All Possible Full Binary Trees

‘All Possible Full Binary Trees(Medium)`


📌 Problem

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

📌 Answer

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    Map<Integer , List<TreeNode>> map = new HashMap<>();
    
    public List<TreeNode> allPossibleFBT(int n) {
        
        if (!map.containsKey(n)) {
            List<TreeNode> res = new ArrayList<>();

            if (n == 1) {
                res.add(new TreeNode(0,null,null));
            } else {
                for (int i = 1 ; i < n ; i += 2) {
                    List<TreeNode> leftSubtree = allPossibleFBT(i);
                    List<TreeNode> rightSubtree = allPossibleFBT(n - i - 1);

                    for (TreeNode left : leftSubtree) {
                        for (TreeNode right : rightSubtree) {
                            res.add(new TreeNode(0,left,right));
                        }
                    }
                }
            }
            map.put(n , res);
        }
        
        return map.get(n);
    }
}
This post is licensed under CC BY 4.0 by the author.

[Easy] Power of Two

[Easy] N-th Tribonacci Number

Comments powered by Disqus.