Advertisement
Guest User

Untitled

a guest
Nov 18th, 2019
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.14 KB | None | 0 0
  1. /*
  2. https://leetcode.com/problems/all-possible-full-binary-trees/
  3. Runtime: 1 ms, faster than 100.00% of Java online submissions for All Possible Full Binary Trees.
  4. Memory Usage: 40.1 MB, less than 100.00% of Java online submissions for All Possible Full Binary Trees.
  5. */
  6. class Solution {
  7.     private static final Cache CACHE = new Cache();
  8.  
  9.     public List<TreeNode> allPossibleFBT(int N) {
  10.         List<TreeNode> ans = CACHE.tries[N];
  11.         if (ans == null) {
  12.             ans = new ArrayList<>();
  13.             for (int l = 1, r = N - 2; r > 0; l += 2, r -= 2) {
  14.                 for (TreeNode left : allPossibleFBT(l))
  15.                 for (TreeNode right : allPossibleFBT(r)) {
  16.                     TreeNode node = new TreeNode(0);
  17.                     node.left = left;
  18.                     node.right = right;
  19.                     ans.add(node);
  20.                 }
  21.             }
  22.             CACHE.tries[N] = ans;
  23.         }
  24.         return ans;
  25.     }
  26.  
  27.     private static class Cache {
  28.         private List<TreeNode>[] tries = new List[21];
  29.  
  30.         public Cache() {
  31.             tries[1] = Arrays.asList(new TreeNode(0));
  32.         }
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement