首页 > 代码库 > 【leetcode刷题笔记】Unique Binary Search Trees II
【leetcode刷题笔记】Unique Binary Search Trees II
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.
1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3
题解:递归的枚举1~n的每个节点为根节点,然后递归的利用它左边的节点构造左子树,放在一个list里面;再利用它右边的节点构造右子树,也放在一个list里面;最终枚举两个list里面的左子树和右子树,构建一棵树。
代码如下:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; left = null; right = null; } 8 * } 9 */10 public class Solution {11 private ArrayList<TreeNode> generate(int start,int end){12 ArrayList<TreeNode> answer = new ArrayList<TreeNode>();13 if(start > end){14 answer.add(null);15 return answer;16 }17 18 //for every node from start to right,make it as tree root and recursively build its left and right child tree19 for(int i = start; i <= end;i++){20 ArrayList<TreeNode> left = generate(start, i-1);21 ArrayList<TreeNode> right = generate(i+1, end);22 for(TreeNode l:left){23 for(TreeNode r:right){24 TreeNode root = new TreeNode(i);25 root.left = l;26 root.right = r;27 answer.add(root);28 }29 }30 31 }32 33 return answer;34 35 }36 public List<TreeNode> generateTrees(int n) {37 return generate(1,n);38 }39 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。