如何使方法正确停止的条件

问题描述 投票:0回答:0

使用二叉搜索树 wordsAtDepth 遍历每个深度并在同一行打印节点字符值(如果它们在同一深度)。 示例:超人 小号 聚氨酯 急诊室 是 否 Image of Binary Search Tree

 void wordsAtDepth() {
        int depth = 0;
        int numOfNodes;
        Node Current = root;
        Node P1 = Current;
        Node P2 = Current;
        Queue queue = new Queue(32); 
        queue.insert(Current); 

        while (!queue.isEmpty()) {
            numOfNodes = (int) Math.pow(2, depth);
            
            for (int i = 0; i < numOfNodes; i++) {
                //
                if (i == 1){
                    P1 = Current;
                }
                if (i % 2 != 0){
                    P2 = Current;
                }
                Current = queue.peekFront();
                if (Current != null) {
                    System.out.print(Current.cData);
                    queue.insert(Current.leftChild);
                    queue.insert(Current.rightChild);
                    queue.remove();
                }
                else if(queue.peekFront() == null) {
                    queue.insert(null);
                    queue.insert(null);
                    queue.remove();
                }
            }
            System.out.println(" ");
            depth++;
            if(Current == null && P1 == null && P2 == null){
                return;
            }
        }
    }

我一直在尝试找出一种方法来在二叉搜索树中没有其他内容时正确停止 while 循环。 OPTIMAL、SANDY、HAPPY 和 OPTIMAL 之类的词有效,但 DRAGON 无效。示例:龙 -> 丁 增强现实 G 欧 它应该看起来像: 丁 增强现实 G 欧 N

这个条件是强制返回以及 for 循环中的 P1 和 P2 的原因。

if(Current == null && P1 == null && P2 == null){
                return;
            }

作为停止 while 循环的一种方法,但它仅在单词在倒数第二个深度上的最右边或最后一个奇数节点上有一个节点时才有效。

java for-loop while-loop queue binary-search-tree
© www.soinside.com 2019 - 2024. All rights reserved.