Unique Binary Search Tree II

來源:互聯網
上載者:User

標籤:style   blog   color   io   strong   for   ar   div   

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

分析:這道題與unique binary search tree I不同在於我們要產生所以的二叉尋找樹並返回樹的根。同樣我們用遞迴的方法,如果是空樹我們加入一個NULL指標,這個對於簡化代碼是有協助的。
如果在空樹的情況是我們不加入NULL,而是讓<TreeNode *> res為空白,那麼在通過左右兩個子樹組成新樹時,代碼會繁瑣很多。因為我們必須要處理左子樹、右子樹是否為空白總共四種情況。
 1 class Solution { 2 public: 3     vector<TreeNode *> generateTrees(int n) { 4         vector<TreeNode *> res; 5         res = generateBST(1,n); 6         return res; 7     } 8     vector<TreeNode *> generateBST(int left, int right){ 9         vector<TreeNode *> res;10         if(left > right){11             res.push_back(NULL);12             return res;13         }14         for(int i = left; i <= right; i++){15             vector<TreeNode *> lefts = generateBST(left, i-1);16             vector<TreeNode *> rights = generateBST(i+1,right);17             for(auto k:lefts)18                 for(auto j:rights){19                     TreeNode * root = new TreeNode(i);20                     root->left = k;21                     root->right = j;22                     res.push_back(root);23                 }24         }25         return res;26     }27 };

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.