LeetCode95: Unique Binary Search Trees II
Given n, generate all structurally unique BST's (binary search trees) that store values 1... N.
For example,
Given n = 3, your program shocould return all 5 unique BST's shown below.
Confused what "{1, #, 2, 3}" means? > Read more on how binary tree is serialized on OJ. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Examples + examples/MrLnmu661xMzixL + examples/examples + 1 + 6/qsq8v7S1vdXitcDM4s/examples + zb/samples + examples/samples + dPQtv6y5svRy/examples + examples/examples + release/release + subL0cv3yvfW0LXExLPSu8/release/fK99bQtcTEs9K7z + 6jrM/release + DQpydW50aW1lOjI0bXM8L3A + release "brush: java; "> class Solution {public: vector generateTrees(int n) { vector result(1); if(n<=0) return result; return helper(1,n); } vector helper(int begin,int end) { vector result; if(begin==end) { result.push_back(new TreeNode(begin)); return result; } if(begin>end) return result; for(int i=begin;i<=end;i++) { vector leftRoot=helper(begin,i-1); vector rightRoot=helper(i+1,end); if(leftRoot.empty()) { for(int j=0;j left=NULL; base->right=rightRoot[j]; result.push_back(base); } } else if(rightRoot.empty()) { for(int j=0;j left=leftRoot[j]; base->right=NULL; result.push_back(base); } } else { for(int j=0;j left=leftRoot[j]; base->right=rightRoot[k]; result.push_back(base); } } } } return result; } }
Then we can see that we can avoid an optimization to determine whether the left and right subtree is empty. The main technique of this optimization is to use a vector containing a NULL element, so that the left and right subtree can be empty or not.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector
generateTrees(int n) { return helper(1,n); } vector
helper(int begin,int end) { vector
result; if(begin==end) { result.push_back(new TreeNode(begin)); return result; } if(begin>end) { result.push_back(NULL); return result; } for(int i=begin;i<=end;i++) { vector
leftRoot=helper(begin,i-1); vector
rightRoot=helper(i+1,end); for(int j=0;j
left=leftRoot[j]; base->right=rightRoot[k]; result.push_back(base); } } } return result; }};