有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java检查二叉树中的节点是否有子节点?

我是二叉树新手,我想知道如何编写一个方法来检查树中的特定节点是否是叶(没有子节点)

public boolean isChild(int item){
    TreeNode cursor = root;
    if (cursor.getLeft() == null && cursor.getRight() == null){
        return true;
    }
}

这就是我目前所知道的


共 (3) 个答案

  1. # 1 楼答案

    假设二叉树中的整数是唯一的,则必须首先找到具有该整数值的节点。因此,编写一个findNode(int-item)方法,返回与item具有相同值的TreeNode。方法的其余部分很好,但如果if语句不为true,则必须返回false,否则将出现编译错误

    public boolean isChild(int item){
        TreeNode cursor = findNode(item);
        if (cursor.getLeft() == null && cursor.getRight() == null){
            return true;
        }
        return false;
    }
    
  2. # 2 楼答案

    基本上,如果您的二叉树对象具有RightNodeLeftNode实例变量,您应该能够通过以下代码确定节点是否为叶:

       public static boolean isLeaf(TreeNode tree){
             if(tree.getRight() == null && tree.getLeft() == null){
                return true;
             }
             return false;
        }
    

    另外,我不太理解int item作为方法参数的用途

  3. # 3 楼答案

    TreeNode cursor = root;
    

    上面这一行会使你的代码出错。因为每次调用isChild(),函数只会检查root是否有左右子级

    您的isChild()函数应该将树node作为参数,并检查此node是否有子级

    根据您的需要:

    if a particular node in the tree is a leaf

    因此,请尝试以下方法:

    // the following function returns true if currnetNode is a leaf, false otherwise
    public boolean isLeaf(TreeNode currnetNode){
        //assuming that caller already checked currnetNode is not null
        if (currnetNode.getLeft() == null && currnetNode.getRight() == null){
            return true;
        }
        return false;
    }