For example,
Given n = 3, your program should return all 5 unique BST's shown below.
1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
confused what
"{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ./** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; left = null; right = null; } * } */ public class Solution { public List<TreeNode> generateTrees(int n) { // Use a nested for-loop to go through every possible combinations of left tree and right tree for a given root. // Do it recursively because it’s the same for the left tree and right tree of root. return genTrees(1, n); } private List<TreeNode> genTrees(int start, int end) { List<TreeNode> list = new LinkedList<>(); // Return null branch if (start > end) { list.add(null); return list; } // Root node traversal from #start to #end for (int i = start; i <= end; i++) { // Get all of the possible left branches List<TreeNode> lefts = genTrees(start, i - 1); // Get all of the possible right branches List<TreeNode> rights = genTrees(i + 1, end); // Nested for-loop is similar to "Unique Binary Search Trees" // The combinations is combination(left)*combination(right) for (TreeNode left : lefts) { for (TreeNode right : rights) { TreeNode node = new TreeNode(i); node.left = left; node.right = right; list.add(node); } } } return list; } }
No comments:
Post a Comment