[英]How to find all rooted subtrees of at most size K in a given binary tree?
如题。 如何有效地生成与原始二叉树共享同一根的所有子树?
这与生成所有大小为 k 的未标记二叉树非常相似,其算法如下所示:
trees(k):
if k is zero:
yield the null tree
else:
for i from 0 to k-1:
for l in trees(i):
for r in trees(k-i):
yield the tree whose root has left subtree l
and right subtree r
你应该能够在你最喜欢的编程语言中找到一个具体的实现。
为了解决这个问题,我们修改了这段代码,将给定的树与递归分开。
subtrees(T, k):
if k is zero:
yield the null tree
else if T is not null:
let L be the left subtree of T's root
let R be the right subtree of T's root
for i from 0 to k-1:
for l in subtrees(L, i):
for r in subtrees(R, k-i):
yield the tree whose root has the same value as T's,
with left subtree l and right subtree r
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.