Advertisement
Guest User

Untitled

a guest
Nov 18th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.92 KB | None | 0 0
  1. /*
  2. Runtime: 2 ms, faster than 94.60% of Java online submissions for All Possible Full Binary Trees.
  3. Memory Usage: 42.1 MB, less than 100.00% of Java online submissions for All Possible Full Binary Trees.
  4. */
  5. class Solution {
  6.     public List<TreeNode> allPossibleFBT(int N) {
  7.         if ((N & 1) == 0) return Collections.emptyList();
  8.         List<TreeNode>[] dp = new List[N + 1];
  9.         dp[1] = Arrays.asList(new TreeNode(0));
  10.         for (int i = 3; i <= N; i += 2) {
  11.             List<TreeNode> ans = dp[i] = new ArrayList<>();
  12.             for (int l = 1, r = i - 2; r > 0; l += 2, r -= 2) {
  13.                 for (TreeNode left : dp[l])
  14.                 for (TreeNode right : dp[r]) {
  15.                     TreeNode node = new TreeNode(0);
  16.                     node.left = left;
  17.                     node.right = right;
  18.                     ans.add(node);
  19.                 }
  20.             }
  21.         }
  22.         return dp[N];
  23.     }
  24. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement