【问题标题】:Remove all subtrees below depth k from the original tree?从原始树中删除深度k以下的所有子树?
【发布时间】:2018-03-08 09:59:10
【问题描述】:

我完全被这个问题困住了,不知道从哪里开始。我给它的每一个测试它都失败了,但我不知道如何修复它。指令是: 从原始树中删除深度k以下的所有子树

相关信息: - 不要更改节点类。 - 不要更改任何函数的第一行:名称、参数、类型。 您可以添加新功能,但不要删除任何内容
- 函数必须是递归的 - 没有循环 - 每个函数必须只有一个递归辅助函数,您可以添加它 - 每个函数必须是独立的 --- 不要调用除了助手之外的任何函数 - 没有字段(在函数之外声明的变量)

如果您认为我遗漏了任何信息/代码,请告诉我。

相关代码:

private Node root;
private static class Node {
    public final int key;
    public Node left, right;
    public Node(int key) { this.key = key; }
}



public void removeBelowDepth(int k) {
    removeBelowDepthHelper(root, 0, k);
    }
private void removeBelowDepthHelper(Node node, int currentDepth, int k) {
    if (node == null) return;
    if (currentDepth == k) {
        node = null;
        return;
    }
    removeBelowDepthHelper(node.left, currentDepth + 1, k);
    removeBelowDepthHelper(node.right, currentDepth + 1, k);
    }

【问题讨论】:

  • 提示#1:在你的辅助函数中将node设置为null实际上并没有做任何事情。它只是一个参数,当您的函数退出时会忘记它。您必须将其他内容设置为 null
  • 如果我理解正确,您想删除树中严格低于某个删除深度的所有节点?在这种情况下,递归到该深度并将左右孩子设置为空。重点是访问将要从树中删除的所有节点(从左到右或从右到左)。

标签: java recursion binary-tree binary-search-tree


【解决方案1】:

我接受了 AJ 的建议,只是更改了 null 调用,它完美地工作!非常感谢你们!

public void removeBelowDepth(int k) {
        removeBelowDepthHelper(root, 0, k);
        }
        private void removeBelowDepthHelper(Node node, int currentDepth, int k) {
        if (node == null) return;
        if (currentDepth == k) {
            node.left = null;
            node.right = null;
            return;
        }
        removeBelowDepthHelper(node.left, currentDepth + 1, k);
        removeBelowDepthHelper(node.right, currentDepth + 1, k);
        }

【讨论】:

  • 完美。请记住将此答案标记为解决问题(单击右侧的灰色复选标记将其变为绿色)。
  • 两天后我可以接受,但我一定会做到的!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-20
  • 2012-09-27
  • 1970-01-01
  • 2021-09-20
  • 1970-01-01
  • 2014-02-08
相关资源
最近更新 更多