leetcode OJ Unique Binary Search Trees

来源:互联网 发布:网络批发服装 编辑:程序博客网 时间:2024/05/16 17:26

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-n中选一个数作为树根,在递归求取两边的子树的二叉查找树的个数,以这个数为树根的二叉查找树的总个数就是左右子树查找树个数的乘积,再把n个这样的情况相加

class Solution {public:    int numTrees(int n) {        return counter(1,n);    }    int counter(int low,int high){        int sum=0;        if(high-low==0){            return 1;        }else if(high-low==1){            return 2;        }        else{            for(int i=low+1;i<high;i++){                sum+=counter(low,i-1)*counter(i+1,high);            }            sum+=counter(low,high-1)+counter(low+1,high);        }        return sum;    }};


0 0
原创粉丝点击