【问题标题】:Remove leaves from a binary tree using recursion使用递归从二叉树中删除叶子
【发布时间】:2015-07-19 04:42:35
【问题描述】:

我尝试使用此逻辑执行此操作,但出现错误

public static void removeLeaves(BinaryTreeNode<Integer> root) {
    BinaryTreeNode<Integer> temp = root;   
    if (root == null) {
        return;
    }
    if (root.left == null && root.right == null) {
        root = null;
    }

    removeLeaves(temp.left);
    removeLeaves(temp.right);
}

整棵树按原样打印。请在不改变我的逻辑的情况下帮助我。

【问题讨论】:

  • 如果逻辑有缺陷,如果不允许我们更改逻辑,就很难提出更正建议。只是想我会指出这一点,以防你的意思不同。

标签: java algorithm binary-tree


【解决方案1】:

在你的 if 语句中

if(root.left==null && root.right==null)
{
    BinaryTreeNode<Integer> temp = null;
    root = temp;
}

您将 root 声明为 temp,它为 null,然后将该 temp 传递给 removeLeaves 函数。因此,当 if 语句为真时,您将 null 传递给该函数。

【讨论】:

  • 你能在不改变我大部分逻辑的情况下为我的问题提出一个解决方案吗?
【解决方案2】:
BinaryTreeNode<Integer> temp = null;
root = temp;

基本上将root 设置为null 然后你调用root.left => NPE

您可能想要添加必要的空检查,并可能重新考虑您的整个函数。

【讨论】:

  • 你能在不改变我大部分逻辑的情况下为我的问题提出一个解决方案吗
【解决方案3】:

您需要单独检查每个根是否为空。你的 if 语句

    if(root.left==null && root.right==null)
    {
       BinaryTreeNode<Integer> temp = null;
       root = temp;
    }

只检查两个根是否为空。但是说没有左叶(root.left 为空)只有右叶,你还是在左边执行

    removeLeaves(root.left);

但是,我们已经知道 root.left 为空。我建议在每次调用 removeLeaves() 或修改现有的 if 语句之前添加单独的检查。

【讨论】:

    【解决方案4】:

    我不相信这不是家庭作业,但这里是。

    null 异常是因为你仍然在调用 removeLeaves() ,即使左右两边都为空。您是否尝试在主 IF() 之后放置 else ?

    public static void removeLeaves(BinaryTreeNode<Integer> root)
    {
        if(root == null)  
        {
            return; // enclosing conditionals in braces is better form, saves lots of headaches later
        }
    
    
        if(root.left==null && root.right==null)
        {
            BinaryTreeNode<Integer> temp = null;
            root = temp;
        }
        else //at least one is not null
        {
            removeLeaves(root.left);
            removeLeaves(root.right);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-17
      • 2015-04-08
      • 2018-03-04
      • 1970-01-01
      • 2016-01-24
      • 2013-06-15
      • 1970-01-01
      相关资源
      最近更新 更多