Advertisement
ogv

Untitled

ogv
Nov 18th, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 KB | None | 0 0
  1. // Runtime: 1 ms, faster than 100.00% of Java online submissions for All Possible Full Binary Trees.
  2. // Memory Usage: 43.6 MB, less than 100.00% of Java online submissions for All Possible Full Binary Trees.
  3. class Solution {
  4.     public List<TreeNode> allPossibleFBT(int N) {
  5.         if (N % 2 == 0) return new ArrayList<TreeNode>();
  6.    
  7.         return list(N, new List[N + 1]);        
  8.     }
  9.    
  10.     private List<TreeNode> list(int N, List<TreeNode>[] dp) {
  11.         if (dp[N] != null) return dp[N];
  12.        
  13.         List<TreeNode> results = new ArrayList<>();            
  14.        
  15.         if (N > 1) {            
  16.             for (int i = 1; i <= N - 2; i += 2) {
  17.                 for (TreeNode left: list(i, dp))
  18.                     for (TreeNode right: list(N - 1 - i, dp)) {
  19.                         TreeNode r = new TreeNode(0);
  20.                         r.left = left;
  21.                         r.right = right;
  22.                         results.add(r);
  23.                     }
  24.             }
  25.         } else {
  26.             results.add(new TreeNode(0));
  27.         }
  28.        
  29.         dp[N] = results;
  30.         return results;
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement