From ea31c63cb1e8aebe6e553fd5d5744174b522db45 Mon Sep 17 00:00:00 2001 From: ANSHU KUMAR <39401992+Anshuvats@users.noreply.github.com> Date: Thu, 3 Oct 2019 00:14:26 +0530 Subject: [PATCH] Added UniqueBinarySearchTrees2 in java --- UniqueBinarySearchTrees2.java | 36 +++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 UniqueBinarySearchTrees2.java diff --git a/UniqueBinarySearchTrees2.java b/UniqueBinarySearchTrees2.java new file mode 100644 index 00000000..c05f3585 --- /dev/null +++ b/UniqueBinarySearchTrees2.java @@ -0,0 +1,36 @@ +/** + * Definition for a binary tree node. + * public class TreeNode { + * int val; + * TreeNode left; + * TreeNode right; + * TreeNode(int x) { val = x; } + * } + */ +class Solution { + public List<TreeNode> generateTrees(int n) { + if(n == 0) return new LinkedList<TreeNode>(); + return generateSubtrees(1, n); + } + + public List<TreeNode> generateSubtrees(int s, int e) { + List<TreeNode> res = new LinkedList<>(); + if(s > e) { + res.add(null); + return res; + } + for(int i = s; i <= e; i++) { + List<TreeNode> left = generateSubtrees(s, i-1); + List<TreeNode> right = generateSubtrees(i+1, e); + for(TreeNode l: left) { + for(TreeNode r: right) { + TreeNode n = new TreeNode(i); + n.left = l; + n.right = r; + res.add(n); + } + } + } + return res; + } +}