【发布时间】:2017-01-05 20:34:58
【问题描述】:
我正在尝试编写这个函数:
struct treeNode *pruneTree(struct treeNode *root, int depth);
给定一棵像这样的树:
1 level 0
/ \
2 3 level 1
/ \ \
4 5 6 level 2
/ \
7 8 level 3
如果 depth = 1 则创建一个 depth = 1 的树并切割之后的所有内容,因此结果应该是:
1
/ \
2 3 // tree with depth = 1
我知道如何编写一个修剪叶子的函数,我正在尝试使其适应任何级别的修剪:
int isLeaf (struct treeNode * treeNode) {
return (treeNode->left == NULL) && (treeNode->right == NULL);
}
void removeLeaves(struct treeNode * root) {
if (root->left != NULL) {
if (isLeaf (root->left)) {
free(root->left);
}
else {
removeLeaves(root->left);
}
}
if (root->right != NULL) {
if (isLeaf (root->right)) {
free(root->right);
}
else {
removeLeaves(root->right);
}
}
}
有什么好的策略来做到这一点?我的方法是用isAfterDepth 函数替换isLeaf 函数并使用计算深度的辅助函数,但这似乎效率不高。有什么更优雅的方式来做到这一点?
【问题讨论】:
-
不应该先
free/delete节点吗?这看起来像是一个会产生内存泄漏的程序。 -
我修改了程序以反映这一点。
-
另一个问题:你只做一个副本?你不改变给定的树?
-
现在我可以修改原始树了。我有一个函数 cloneTree 可以用来不改变原始文件。
标签: c data-structures tree