开发者

Simple binary tree question

开发者 https://www.devze.com 2023-02-12 14:24 出处:网络
I was wanting to display all of the nodes at a certain level in the tree: Called by: allNodesAtACertainLevel(0, *whatever level you want*, root);

I was wanting to display all of the nodes at a certain level in the tree:

Called by: allNodesAtACertainLevel(0, *whatever level you want*, root);

This produces the correct answer.

private void allNodesAtACertainLevel(int count, int level, 开发者_StackOverflow中文版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);
        }

    }

This doesn't.

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);
        }

    }

Could someone explain why?


The second example increments count twice, the first example increments count only once. Also the first increments count before calls to allNodesAtACertainLevel while second example calls allNodesAtACertainLevel and increments count after the call.

Any of these should produce a correct result when substituted appropriately for the second example:

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);


Your problem is because you are making count++ to times, so you increment the level counter one extra time.

You should change your code to the following:

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

精彩评论

暂无评论...
验证码 换一张
取 消