我想在树中的某个级别上显示所有节点:

呼叫者:allNodesAtACertainLevel(0, *whatever level you want*, root);

这将产生正确的答案。

private void allNodesAtACertainLevel(int count, int level, Node n){

        count += 1;

        if(count <= level){
            if(n.left != null) allNodesAtACertainLevel(count, level, n.left);
            if(n.right != null) allNodesAtACertainLevel(count, level, n.right);
        }
        else{
            System.out.print(n.value);
        }

    }


不是这样

private void allNodesAtACertainLevel(int count, int level, Node n){

        if(count < level){
            if(n.left != null) allNodesAtACertainLevel(count++, level, n.left);
            if(n.right != null) allNodesAtACertainLevel(count++, level, n.right);
        }
        else{
            System.out.print(n.value);
        }

    }


有人可以解释为什么吗?

最佳答案

第二个示例将count递增两次,第一个示例仅将count递增一次。同样,第一个示例在调用count之前递增allNodesAtACertainLevel,而第二个示例调用allNodesAtACertainLevel,在调用之后递增count

当适当地替代第二个示例时,这些方法中的任何一个都应产生正确的结果:

count++;
if(n.left != null) allNodesAtACertainLevel(count, level, n.left);
if(n.right != null) allNodesAtACertainLevel(count, level, n.right);


-

count += 1;
if(n.left != null) allNodesAtACertainLevel(count, level, n.left);
if(n.right != null) allNodesAtACertainLevel(count, level, n.right);


-

if(n.left != null) allNodesAtACertainLevel(count+1, level, n.left);
if(n.right != null) allNodesAtACertainLevel(count+1, level, n.right);

关于java - 简单的二叉树问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5086368/

10-16 10:00