[LeetCode] 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 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}".
Analysis:

The basic idea is still using the DFS scheme. It is a little hard to think the structure of the argument list in the function. It is clear that for each tree/subtree, we will set the root as the start position to the end position, and recursively construct the left subtree with the left part and the right subtree with the right part.
So first we can have
 void dfs (int st, int ed     ){
   if (st>ed) {   // generate a null node }
  else{
    for (int i=st;i<=ed;i++){
        
      dfs(st,i-1,   );     //generate left subtree 
      dfs(i+1,ed,   );  // generate right subtree
    }
  }

}
Next step is to think about how to store all the possible solutions.
This is important ! Think about the root node, all the possible solutions of the tree are from the combinations of all the possible solutions of its left subtree, and its right subtree. One step further, if we have a root node and a left node, for the left node, still the subtrees below it are the combinations of the possible solutions of its left and right subtree, until the leaf node.

In other words, we store all the possible solutions for each node, instead of storing the only tree. So, we can have
void dfs(int st, int ed, vector<TreeNode *> res){}
in this function, recursively generate the left tree and right tree, then construct the current node, and push it to the current solution vector.
Details see the code.
c++
void treeGenerate(int st,int ed,vector<TreeNode *> &res){
        if (st>ed){
            res.push_back(NULL);
        }else{
            for (int i=st;i<=ed;i++){
                vector<TreeNode *> lefts;
                treeGenerate(st,i-1,lefts);
                vector<TreeNode *> rights;
                treeGenerate(i+1,ed,rights);
                 
                for (int li = 0; li<lefts.size();li++) {
                    for (int ri =0; ri<rights.size();ri++){
                        TreeNode* node = new TreeNode(i);
                        node->left=lefts[li];
                        node->right=rights[ri];
                        res.push_back(node);
                    }
                }
            }
        }
    }
     
    vector<TreeNode *> generateTrees(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<TreeNode*> res;
        treeGenerate(1,n,res);
        return res;
    }


java
public class Solution {
    ArrayList<TreeNode> result;
	
	public ArrayList<TreeNode> generateTrees(int n) {
        result = new ArrayList<TreeNode>();
		dfsTree(1, n,result);
        return result;
    }
	public void dfsTree(int start, int end, ArrayList<TreeNode> res){
		if(start>end) res.add(null);
		else{
			for(int i = start;i<=end;i++){
				ArrayList<TreeNode> leftNodes = new ArrayList<TreeNode>();
				dfsTree(start, i-1, leftNodes);
				ArrayList<TreeNode> rightNodes = new ArrayList<TreeNode>();
				dfsTree(i+1, end, rightNodes);
				for(int li = 0;li<leftNodes.size();li++){
					for(int ri = 0;ri<rightNodes.size();ri++){
						TreeNode node = new TreeNode(i);
						node.left = leftNodes.get(li);
						node.right = rightNodes.get(ri);
						res.add(node);
					}
				}
			}
		}
	}
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值