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
分析:
遞歸即可。枚舉所有的 root 節點,root 的左子樹和右子樹就是兩個子問題,遞歸求解。
但是有一點要注意,容易出錯。
如果子樹的節點個數為零,這時候返回的應該是一個包含 NULL 的 vector;
/** * 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 generateTrees(int n) { vector res; if(n == 0){ res.push_back(NULL); return res; } return generateTrees(1, n); } private: vector generateTrees(int left, int right) { TreeNode *node(NULL); vector trees, left_tree, right_tree; if(left > right) { trees.push_back(NULL); return trees; } for(int i=left; i<=right; ++i) { left_tree = generateTrees(left, i-1); right_tree = generateTrees(i+1, right); for(auto j : left_tree) for(auto k : right_tree) { node = new TreeNode(i); node->left = j; node->right = k; trees.push_back(node); } } return trees; } };