Redian新闻
>
generate all distinct full binary trees with n leaves
avatar
generate all distinct full binary trees with n leaves# JobHunting - 待字闺中
s*1
1
大家好
有道binary Tree 的题请教大家,generate all structurally distinct full binary
trees with n leaves, "full" means all internal (non-leaf) nodes have
exactly two children. For example, there are 5 distinct full binary trees
with 4 leaves each.
着重想问下 如何用DP解决呢?
多谢多谢!
avatar
x*y
2
Let F(n, k) to be # of different structures with n leaves and k leaves in
the lowest level. k must be even to be valid.
F(n, k) =
sum{ k/2 <= i <= n-k/2 and i is even } F(n-k/2, i) C(i, k/2)
with F(j, j) = 1 when j is power of 2
and F(j, j) is invalid if not.
For your example, it's F(4,4)+F(4,2)
F(4,4) =1
F(4,2) = F(3, 2) C(2, 1) = F(2,2)C(2,1)C(2,1) = 4
So totaly 5.
avatar
s*1
3
Thank you so much. Would you please walk me through the algorithm a little,
because the hardest part k/2 <= i <= n-k/2 I haven't figured out.
Thanks again.
In addition, if I want to print out all the trees in dotted parenthesized
form, recursion is a good way? Or iterator? I have no clue on that? Can you
please give me some hint?
Thanks again.

【在 x***y 的大作中提到】
: Let F(n, k) to be # of different structures with n leaves and k leaves in
: the lowest level. k must be even to be valid.
: F(n, k) =
: sum{ k/2 <= i <= n-k/2 and i is even } F(n-k/2, i) C(i, k/2)
: with F(j, j) = 1 when j is power of 2
: and F(j, j) is invalid if not.
: For your example, it's F(4,4)+F(4,2)
: F(4,4) =1
: F(4,2) = F(3, 2) C(2, 1) = F(2,2)C(2,1)C(2,1) = 4
: So totaly 5.

avatar
i*h
4
F(n) = F(1)*F(n-1) + F(2)*F(n-2) + ... + F(k)*F(n-k) + ...
avatar
s*1
5
Thank you All.
Allow me to summarize the Dynamic Programming:
Let T(n) be the number of distinct full trees and n the parameter for the
number of leaves
So T(n) = T(n-1)*T(1)+T(n-2)*T(2)+...+T(2)*T(n-2)+T(1)*T(n-1)
and T(1)=1 T(2)=1
Thus, build up a table first, lookup the table if there is we want then use
it, if not update the table for the future use.
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。