Given n, generate all structurally unique BST‘s (binary search trees) that store values 1...n.
For example,
Given n = 3, your program should return all 5 unique BST‘s shown below.
解题思路:
参考Java for LeetCode 096 Unique Binary Search Trees思路,本题很容易解决。注意,如果试图不复制而使用对象的引用,是无法得到正确结果的,当然也可采用DFS的思路,但是考虑到JAVA面向对象的特征,我们还是采用Java for LeetCode 096 Unique Binary Search Trees的思路吧。
JAVA实现如下:
static public List<TreeNode> generateTrees(int n) { List<TreeNode> list = new ArrayList<TreeNode>(); if (n == 0) { list.add(null); return list; } if (n == 1) { list.add(new TreeNode(1)); return list; } for (int k = 0; k <= n - 1; k++) { List<TreeNode> left = generateTrees(k); List<TreeNode> right = generateTrees(n - k - 1); for (TreeNode rightNode : right) plus(rightNode, k + 1); for (TreeNode leftNode : left) { for (TreeNode rightNode : right) { TreeNode TN = new TreeNode(k + 1); TN.left = treeNodeClone(leftNode); TN.right = treeNodeClone(rightNode); list.add(TN); } } } return list; } public static void plus(TreeNode root, int num) { if (root == null) return; root.val += num; plus(root.left, num); plus(root.right, num); } public static TreeNode treeNodeClone(TreeNode TN1){ if(TN1==null) return null; TreeNode TN2=new TreeNode(TN1.val); TN2.left=treeNodeClone(TN1.left); TN2.right=treeNodeClone(TN1.right); return TN2; }
时间: 2024-11-03 20:45:39