二叉树的最大宽度-java代码

wfsdck30  于 2021-07-03  发布在  Java
关注(0)|答案(2)|浏览(333)

**结束。**此问题不符合堆栈溢出准则。它目前不接受答案。
**想改进这个问题吗?**更新问题,使其成为堆栈溢出的主题。

三年前关门了。
改进这个问题
问题是:
给定一个二叉树,写一个函数来获得给定树的最大宽度。树的宽度是所有等级中的最大宽度。二叉树的结构与完全二叉树相同,但有些节点为空。
一个级别的宽度定义为结束节点(级别中最左侧和最右侧的非空节点)之间的长度,其中结束节点之间的空节点也计入长度计算。
这是我的密码:

public class MaxWidth {
    public int widthOfBinaryTree(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int maxWidth = queue.size();

        while (! queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode rootCur = queue.poll();
                if (rootCur.left != null) {
                    queue.offer(root.left);
                }
                if (rootCur.right != null) {
                    queue.offer(root.right);
                }
            }

            if (queue.size() > maxWidth) {
                maxWidth = queue.size();
            }
        }

        return maxWidth;
    }
}

然而,这最终是一个无休止的循环~我不知道为什么?谢谢!
补充:输入树结构为:

1
           3        2
         5   3        9
9udxz4iz

9udxz4iz1#

问题在于:

if (rootCur.left != null) {
    queue.offer(root.left); // this is not rootCur!
}
if (rootCur.right != null) {
    queue.offer(root.right); // this is not rootCur!
}
qni6mghb

qni6mghb2#

if (rootCur.left != null) {
    queue.offer(root.left); ==> Change root to rootCur
}
if (rootCur.right != null) {
    queue.offer(root.right); ==> Change root to rootCur
}

您正在添加root.left和root.right中的元素,因此队列永远不会耗尽。

相关问题