1. 程式人生 > >資料結構-----Unique Binary Search Trees II (唯一二叉排序樹的個數)

資料結構-----Unique Binary Search Trees II (唯一二叉排序樹的個數)

Unique Binary Search Trees II 

題目描述:(輸出用1–n這幾個數字能組成的所有BST.

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
confused what"{1,#,2,3}"means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
   1
  / \
 2   3
    /
   4
    \
     5
The above binary tree is serialized as"{1,2,3,#,#,4,#,#,5}".

思路:

BST(二叉排序樹):中序遍歷的結果為非遞減序列,並且節點(個數和值)相同的不同二叉樹的中序遍歷結果都相同;

當左子樹的節點個數確定後,右子樹的個數也隨之確定;

當節點個數為0或1時,二叉樹只有1種,表示為f(0)=1,f(1)=f(0)*f(0);

當節點個數為2時,總的種類數=左子樹為空f(0)*右子樹不為空f(1)+左子樹不為空f(1)*右子樹為空f(0),即f(0)*f(1)+f(1)*f(0)=2種;

當節點個數為3時,有左子樹為空f(0)*右子樹不為空f(2)+左子樹不為空f(2)*右子樹為空f(0)+左右子樹均不為空f(1)*f(1),即f(0)*f(2)+f(2)*f(0)+f(1)*f(1)=1*2+2*1+1*1=5種;

……

當節點個數為n時,結果為f(0)*f(n-1)+f(1)*f(n-2)+……+f(n-2)*f(1)+f(n-1)*f(0);

/**
 * Definition for binary tree
 * 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 helper(1, 0);//一個節點就能建立一棵樹,為了減少遞迴
        return helper(1,n);//將結點個數傳進去
    }
private:
    vector<TreeNode*> helper(int start,int end)
    {
        vector<TreeNode*> subTree;
        if(start>end)//判斷
        {
            subTree.push_back(NULL);
            return subTree;
        }
        for (int k = start; k <= end; k++)
        {
           // 假設k為根節點,根節點左邊是左子樹,右邊是右子樹,一分為二,依次往下遞迴
            //返回不同二叉樹的根節點,有幾個就返回幾個根節點,然後裝進容器裡面
           vector<TreeNode*> leftSubs = helper(start, k - 1);
           vector<TreeNode*> rightSubs = helper(k + 1, end);
            //左子右子樹和根節點結合
            //以k為根節點的樹的個數,等於左子樹的個數乘以右子樹的個數
           for(int i=0;i<leftSubs.size();i++)//for (auto i : leftSubs)
           {
             for(int j=0;j<rightSubs.size();j++)// for (auto j : rightSubs)
              {
                TreeNode *node = new TreeNode(k);//為每個樹申請新空間
                node->left =leftSubs[i];//左子樹
                node->right = rightSubs[j];//右子樹
                subTree.push_back(node);//根節點
              }
            }
        }
        return subTree;//返回樹
    }      
};