095 Unique Binary Search Trees II 不同的二叉查找树 II
给出 n,问由 1...n 为节点组成的不同的二叉查找树有多少种?
例如,
给出 n = 3,则有 5 种不同形态的二叉查找树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
详见:https://leetcode.com/problems/unique-binary-search-trees-ii/description/
Java实现:
/** * 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<TreeNode>(); } return generateTrees(1,n); } private ArrayList<TreeNode> generateTrees(int left, int right){ ArrayList<TreeNode> res = new ArrayList<TreeNode>(); if (left > right){ res.add(null); return res; } for (int i = left; i <= right; i++){ ArrayList<TreeNode> lefts = generateTrees(left, i-1);//以i作为根节点,左子树由[1,i-1]构成 ArrayList<TreeNode> rights = generateTrees(i+1, right);//右子树由[i+1, n]构成 for (int j = 0; j < lefts.size(); j++){ for (int k = 0; k < rights.size(); k++){ TreeNode root = new TreeNode(i); root.left = lefts.get(j); root.right = rights.get(k); res.add(root);//存储所有可能行 } } } return res; } }