给出 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) { List<TreeNode> res=new ArrayList<TreeNode>(); if(n<1){ return res; } 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; } }
C++实现:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<TreeNode*> generateTrees(int n) { if(n==0) { return vector<TreeNode*>(); } return buildTree(1,n); } vector<TreeNode*> buildTree(int start,int end) { vector<TreeNode*> trees; if(start>end) { trees.push_back(nullptr); return trees; } if(start==end) { trees.push_back(new TreeNode(start)); return trees; } for(int i=start;i<=end;++i) { vector<TreeNode*> leftTree=buildTree(start,i-1); vector<TreeNode*> rightTree=buildTree(i+1,end); for(int j=0;j<leftTree.size();++j) { for(int k=0;k<rightTree.size();++k) { TreeNode *root=new TreeNode(i); root->left=leftTree[j]; root->right=rightTree[k]; trees.push_back(root); } } } return trees; } };