递归(~o▔▽▔)~o o~(▔▽▔o~)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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 < 1) { | |
return new ArrayList<>(); | |
} | |
return generateBST(1, n); | |
} | |
private List<TreeNode> generateBST(int start, int end) { | |
List<TreeNode> result = new ArrayList<>(); | |
if (start > end) { | |
result.add(null); // !!! | |
return result; | |
} | |
if (start == end) { | |
result.add(new TreeNode(start)); | |
return result; | |
} | |
for (int i = start; i <= end; i++) { | |
List<TreeNode> leftChildren = generateBST(start, i - 1); | |
List<TreeNode> rightChildren = generateBST(i + 1, end); | |
for (TreeNode left : leftChildren) { | |
for (TreeNode right : rightChildren) { | |
TreeNode root = new TreeNode(i); | |
root.left = left; | |
root.right = right; | |
result.add(root); | |
} | |
} | |
} | |
return result; | |
} | |
} |
没有评论:
发表评论