【问题标题】:Recursively deleting a BST递归删除 BST
【发布时间】:2017-01-19 16:14:05
【问题描述】:

我有一个 BST,想在达到一定深度后修剪树。我在尝试遍历树时遇到NullPointerException,将节点设置为超过想要的深度为空。

我的逻辑与我在这里所做的事情是否正确?这似乎是一个非常简单的问题,但我似乎无法理解导致此错误的原因。

public void clip(int d) {
    int counter = 0;
    clip_helper(d, root, counter);
}

public void clip_helper(int depth, Node n, int c) {

    if (n != null) {
        c++;
        if (c == depth) {
            n.left = null;
            n.right = null;
        }
    }
    clip_helper(depth, n.left, c);
    clip_helper(depth, n.right, c);
}

*还应该补充一点,我对递归解决方案还很陌生,所以我可能会遗漏一些明显的东西。

【问题讨论】:

    标签: java recursion binary-search-tree


    【解决方案1】:
    clip_helper(depth, n.left, c);
    clip_helper(depth, n.right, c);
    

    这些行导致 NullPointer 异常,因为您的程序永远不会结束 即使节点 n 为空,它仍然会向左和向右移动,这是造成这种情况的原因

    要解决这个问题,只需在代码顶部添加一个空检查条件

    if(n==null)
       return;
    

    【讨论】:

      【解决方案2】:

      你应该改变:

      clip_helper(depth, n.left, c);
      clip_helper(depth, n.right, c);
      

      到:

      if(n.left!=null && n.right!=null) {
          clip_helper(depth, n.left, c);
          clip_helper(depth, n.right, c);
      }
      

      或:

      if(c==depth) {
          clip_helper(depth, n.left, c);
          clip_helper(depth, n.right, c);
      }
      

      因为clip_helper的递归调用不会停止。

      【讨论】:

        【解决方案3】:

        如果 Node 为空,你应该返回如下

        public void clip(int d) {
            int counter = 0;
            clip_helper(d, root, counter);
        }
        
        public void clip_helper(int depth, Node n, int c) {
            if(n== null ) return;
            if (n != null) {
                c++;
                if (c == depth) {
                    n.left = null;
                    n.right = null;
                }
            }
            clip_helper(depth, n.left, c);
            clip_helper(depth, n.right, c);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-12-23
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-10
          • 2019-03-14
          • 2020-11-18
          相关资源
          最近更新 更多