Leetcode-96.Unique Binary Search Trees

题目:

Given n, how many structurally unique BST's (binary search trees) that store values 1...n?

For example,
Given n = 3, there are a total of 5 unique BST's.

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

Subscribe to see which companies asked this question

AC代码:

class Solution {
public:
	int numTrees(int n) {
		if (n == 0)return 0;
		if (n == 1)return 1;
		if (n == 2)return 2;
		vector<int>num(n + 1,0);
		num[1] = 1;
		num[2] = 2;
		for (int i = 3; i <= n;i++){//节点个数
			int now = 0;
			for (int root = 1; root <= i; root++){//根节点编号
				int left = root - 1;//根节点左子树的节点的个数
				int right = i - root;
				if (left == 0 || right == 0){
					int temp = left + right;
					now = now + num[temp];
				}
				else now = now + num[left] * num[right];
			}
			num[i] = now;
		}
		return num[n];
	}
};


解析:

题目主要考查对二叉搜索树的性质的了解,题目中所有二叉搜索树的节点的编号都在【1,n】之间,当给定最大编号为n的求其二叉搜索树的个数时,可

问题拆分为当root分别为1.......n时所有的二叉搜索树的总和。那么问题就简单了,那么假设我们当前的root为d,那么根据二叉搜索树的性质,它左子树的

所有节点的编号必须小于d(只可能为1-d-1),右子树的所有节点的编号为(d+1,n)。那么当左边子树的节点个数为d-1个时它可以形成的二叉搜索树个数为

num[d-1],同理root=d时,它的右子树可以构成的二叉搜索树的个数为num[n-d]。。。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值