leetcode95. 不同的二叉搜尋樹 II
阿新 • • 發佈:2018-12-24
給定一個整數 n,生成所有由 1 ... n 為節點所組成的二叉搜尋樹。
示例:
輸入: 3 輸出: [ [1,null,3,2], [3,2,null,1], [3,1,null,null,2], [2,1,3], [1,null,2,null,3] ] 解釋: 以上的輸出對應以下 5 種不同結構的二叉搜尋樹: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
解題思路:
class Solution { public: vector<TreeNode*> generateTrees(int n) { vector<TreeNode*> t; if(n==0) { return t; } return f(1,n); }; vector<TreeNode*> f(int l,int r)//遞迴建立左右子樹 { vector<TreeNode*> ans; if(l>r) { ans.push_back(NULL); } for(int k=l;k<=r;k++)//k為當前對應情況的根節點 { vector<TreeNode*> left=f(l,k-1); vector<TreeNode*> right=f(k+1,r); for(int i=0;i<left.size();i++)//子樹有多種組合的情況 { for(int j=0;j<right.size();j++) { TreeNode *temp=new TreeNode(k); temp->left=left[i]; temp->right=right[j]; ans.push_back(temp); } } } return ans; } };
最開始的思路.......
class Solution { public: vector<TreeNode*> ans; int mark[100000]={0}; vector<TreeNode*> generateTrees(int n) { for(int i=1;i<=n;i++) { memset(mark,0,sizeof(mark)); TreeNode* root=new TreeNode(i); mark[i]=1; ans.push_back(root); f(root,n); } return ans; }; void f(TreeNode* root,int n) { if(root==NULL) { ans.push_back(root); return; } for(int j=1;j<=n;j++) { if(mark[j]==1) continue; if(j<root->val) { mark[j]=1; root->left=new TreeNode(j); ans.push_back(root->left); f(root->left,n); } else if(j>root->val) { mark[j]=1; root->right=new TreeNode(j); ans.push_back(root->right); f(root->right,n); } } } };