LeetCode | 95. Unique Binary Search Trees II

 

题目:

Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.

Example:

Input: 3
Output:
[
  [1,null,3,2],
  [3,2,null,1],
  [3,1,null,null,2],
  [2,1,3],
  [1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

 

题意:

输入整数n,输出由[1, n]个节点组成的各种二叉搜索树。可以使用深度优先搜索进行解决。

 

代码:

/**
 * 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:
    TreeNode* cloneTree(TreeNode* root) {
		TreeNode* new_root = new TreeNode(root->val);

		if (root->left != NULL)
			new_root->left = cloneTree(root->left);
		if (root->right != NULL)
			new_root->right = cloneTree(root->right);

		return new_root;
	}

	vector<TreeNode*> generateTrees(int n) {
		vector<TreeNode*> res;
        if (n < 1)
			return res;
		res.push_back(NULL);

		for (int i = 1; i <= n; i++) 
		{
			vector<TreeNode*> update_res;
			for (int j = 0; j < res.size(); j++) 
			{
				TreeNode* new_root = new TreeNode(i);
				new_root->left = res[j];
				TreeNode* new_res = cloneTree(new_root);
				delete new_root;
				update_res.push_back(new_res);
			}

			for (int j = 0; j < res.size(); j++) 
			{
				TreeNode* cur_root = res[j];
				if (cur_root == NULL)
					continue;
				TreeNode* cur_parent = cur_root;
				TreeNode* ori_right = cur_root->right;
				while (1) {
					TreeNode* new_node = new TreeNode(i);
					cur_parent->right = new_node;
					new_node->left = ori_right;
					TreeNode* new_res = cloneTree(cur_root);
					update_res.push_back(new_res);
					cur_parent->right = new_node->left;
					delete new_node;

					if (ori_right == NULL)
						break;
					cur_parent = ori_right;
					ori_right = ori_right->right;
				}
			}
			res = update_res;
		}
		return res;
	}
};

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值