0

I had an assignment a while back. After my professor graded it, he left a comment in the code that said, "simplify logic". He didn't take off any points, but I can't see another way to approach it...what I have makes sense to me, and works. So, could someone tell me a way to improve what I have? Just so I know...

    public void breadthFirstTraversal(){
        breadthFirstTraversal(root);
    }

    private void breadthFirstTraversal(TreeNode<E> node){

        Queue<TreeNode<E>> queue = new LinkedList<>();

        queue.add(node);

        while(!queue.isEmpty()){
            TreeNode<E> temp = queue.poll();
            System.out.print(temp.data + " ");

            if(temp.left != null && temp.right == null){
                queue.add(temp.left);
            }else if(temp.left == null && temp.right != null){
                queue.add(temp.right);
            }else if(temp.left != null && temp.right != null){
                queue.add(temp.left);
                queue.add(temp.right);
            }
        }
    }

Thank you in advance!

1 Answer 1

2

temp.right being null has no effect on whether or not temp.left should be added and temp.left being null has no effect on temp.right being added. You can reduce it to just two ifs as such:

if( temp.left != null ) queue.add( temp.left );
if( temp.right != null ) queue.add( temp.right );
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.