Leetcode 95 不同的二叉搜索树II
题目描述:
题解:首先要了解卡特兰数的递归公式。对于序列[1,2,....n]构成的二叉搜索树,我们按顺序选择i作为根节点,[1,..i-1]构成左子树,[i+1,....n]作为右子树。递归的重复上述操作即可
(之前写树的题返回值都是单个值,这里递归返回值为节点序列,因为有很多种情况)
AC代码:
/** * 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*> Build(int low,int hight) { if(low > hight) return {}; vector<TreeNode* > tmp; // if(low == hight) // { // TreeNode* now = new TreeNode(low); // tmp.push_back(now); // return tmp; // } for(int i=low;i<=hight;i++) { vector<TreeNode*> l = Build(low,i-1); vector<TreeNode*> r = Build(i+1,hight); int Len_l = l.size(); int Len_r = r.size(); if(Len_l == 0) { l.push_back(NULL); Len_l = l.size(); } if(Len_r == 0) { r.push_back(NULL); Len_r = r.size(); } for(int j = 0;j < Len_l;j++) { for(int k = 0;k < Len_r;k++) { TreeNode* now = new TreeNode(i); now->left = l[j]; now->right = r[k]; tmp.push_back(now); } } } return tmp; } vector<TreeNode*> generateTrees(int n) { vector<TreeNode* > ans; ans = Build(1,n); return ans; } };