java - 改进广度优先逻辑

标签 java logic binary-search-tree breadth-first-search

不久前我接到了一个任务。我的教授评分后,他在代码中留下了一条评论:“简化逻辑”。他没有取消任何观点,但我看不到其他方法来解决这个问题……我所拥有的对我来说是有意义的,并且有效。那么,有人可以告诉我一种方法来改善我所拥有的吗?据我所知...

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

提前谢谢您!

最佳答案

temp.right 为 null 对于是否应添加 temp.left 没有影响,而 temp.left 为 null 则没有影响对添加 temp.right 的影响。您可以将其减少到只有两个 if:

if( temp.left != null ) queue.add( temp.left );
if( temp.right != null ) queue.add( temp.right );

关于java - 改进广度优先逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29838149/

相关文章:

Java swing简单通讯录事件错误

java - Android Retrofit 带有安全 header 的 Soap 请求信封

java - 在简单的 Scala 应用程序中嵌入终端窗口

java - 增量器逻辑

Python:使用列表创建二叉搜索树

java - 无法删除带有图像的目录

c - (生命游戏)如何在不检查矩阵外部的情况下循环遍历矩阵的外层,同时检查邻居?

.net - 如何正确记录应用程序的逻辑流程?

algorithm - 如何创建左规范二叉搜索树?

Java二叉搜索树和哈希表