0
votes

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

1 Answers

2
votes

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