Consider I have an array [3,18,15,25,26], how many possible binary search trees can be formed from it?
Consider I have an array [3,18,15,25,26] , how many possible binary search trees can
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
After looking at the question linked by MicSim, I still wasn’t satisfied with that, so I began looking at it myself. Here’s what I came up with…
Each tree can be thought of as two trees with a parent root node. If you know the number of possible combinations of the two children branches separately, the total combinations having that root node is the product of the children combinations.
We can begin building up a higher count solution by solving the lower count instances first.
I will use
C(n)to represent the total possible combinations of n nodes, the Catalan Number.Hopefully these two are obvious:
C(2) is also fairly obvious, but it can be built, so let’s do that. There are two ways to choose the root node. One leaves a child count (left:right) of
1:0and the other0:1. So, the first possibility isC(1)*C(0) = 1*1 = 1. And the second isC(0)*C(1) = 1*1 = 1. Summing those together gives usNothing too exciting yet. Now let’s do 3 nodes. There are 3 ways to choose the root node and, hence, 3 child groupings. Your possible groups are
2:0,1:1and0:2.Based on our prior defintions,
C(3)can be written asC(2)*C(0) + C(1)*C(1) + C(0)*C(2) = 2*1 + 1*1 + 1*2 = 2+1+2 = 5.4 nodes has child groupings of
3:0,2:1,1:2and0:3. So,C(4)can be written asC(3)*C(0) + C(2)*C(1) + C(1)*C(2) + C(0)*C(3) = 5*1 + 2*1 + 1*2 + 1*5 = 5+2+2+5 = 14.Hopefully, two things are beginning to become apparent. First, this will start becoming cumbersome fairly soon. Second, that what I have described, in a fairly long-winded fashion, is the recurrence relation representation on the wiki page.
I don’t know if this helps, but it helped me to go through the exercise, so I thought I’d share. I wasn’t trying to recreate the recurrence relation when I started, so it was good that my results matched one of the existing methods.