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.
#include <iostream> #include <vector> #include <unordered_map> using std::vector; using std::unordered_map; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { private: unordered_map<int, vector<TreeNode*> > PreResult; vector<TreeNode*> generateTrees(int n, int base) { vector<TreeNode*> Result; if (n == 0) { TreeNode* TmpNode = NULL; Result.push_back(TmpNode); return Result; } if (n == 1) { TreeNode* TmpNode = new TreeNode(n + base); Result.push_back(TmpNode); return Result; } for (int HeadIndex = 1; HeadIndex <= n; HeadIndex++) { vector<TreeNode*> LeftChildVector = generateTrees(HeadIndex - 1, base); vector<TreeNode*> RightChildVector = generateTrees(n - HeadIndex, base + HeadIndex); const vector<TreeNode*>::size_type LEFTSIZE = LeftChildVector.size(); const vector<TreeNode*>::size_type RIGHTSIZE = RightChildVector.size(); for (vector<TreeNode*>::size_type IndexOfLeft = 0; IndexOfLeft < LEFTSIZE; IndexOfLeft++) { for (vector<TreeNode*>::size_type IndexOfRight = 0; IndexOfRight < RIGHTSIZE; IndexOfRight++) { TreeNode *TmpHeadNode = new TreeNode(base + HeadIndex); TmpHeadNode->left = LeftChildVector[IndexOfLeft]; TmpHeadNode->right = RightChildVector[IndexOfRight]; Result.push_back(TmpHeadNode); } } } return Result; } public: vector<TreeNode*> generateTrees(int n) { return generateTrees(n, 0); } };
版权声明:本文为博主原创文章,未经博主允许不得转载。
LeetCode_Unique Binary Search Trees II
原文地址:http://blog.csdn.net/sheng_ai/article/details/46683979