美文网首页
662. 不懂Maximum Width of Binary T

662. 不懂Maximum Width of Binary T

作者: 7ccc099f4608 | 来源:发表于2020-07-05 17:01 被阅读0次

https://leetcode-cn.com/problems/maximum-width-of-binary-tree/

image.png

(图片来源https://leetcode-cn.com/problems/maximum-width-of-binary-tree/

日期 是否一次通过 comment
2020-07-05 0

Thoughts

  1. 满树中,根节点序号为idx,则左子节点为2idx,右子节点为2idx+1;
  2. width = max(每一层中最右边的节点编号 - 最左边的节点编号 + 1)

非递归

public int widthOfBinaryTree(TreeNode root) {
        if(root == null) {
            return 0;
        }

        LinkedList<TreeNode> queue = new LinkedList<>();  // 注意不要写成Queue<TreeNode>, 否则没有peekLast/peekFirst方法
        root.val = 1;
        queue.offer(root);
        int res = 0;

        while(! queue.isEmpty()) {
            res = Math.max(res, queue.peekLast().val-queue.peekFirst().val+1);
            int size = queue.size();
            for(int i=0; i<size; i++) {
                TreeNode node = queue.poll();
                if(node.left != null) {
                    node.left.val = 2 * node.val;
                    queue.offer(node.left);
                }

                if(node.right != null) {
                    node.right.val = 2 * node.val + 1;
                    queue.offer(node.right);
                }
            }
        }

        return res;
    }

相关文章

网友评论

      本文标题:662. 不懂Maximum Width of Binary T

      本文链接:https://www.haomeiwen.com/subject/xcbvqktx.html