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
原题链接:https://oj.leetcode.com/problems/unique-binary-search-trees-ii/
思路: 与之前的求二叉搜索树的数量的题一样的思路,只是这里要实际构建树。因为二叉搜索树是这样的树,左节点小于根,根小于右节点。所以任选一个节点 i 作为根,则(1,i) 个数可作为左子树的节点,(i+1,n)个数可作为右子树的节点。所以,只要遍历所有的i,就可以得出所有的树。
public List<TreeNode> generateTrees(int n) { return generateTrees(1,n); } public List<TreeNode> generateTrees(int start,int end) { List<TreeNode> list = new ArrayList<TreeNode>(); if(start>end){ list.add(null); return list; } for(int i=start;i<=end;i++){ List<TreeNode> lefts = generateTrees(start,i-1); List<TreeNode> rights = generateTrees(i+1,end); for(TreeNode left : lefts){ for(TreeNode right : rights){ TreeNode node = new TreeNode(i); node.left = left; node.right = right; list.add(node); } } } return list; } // Definition for binary tree public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }
时间: 2024-10-09 20:55:20