Maximum Width of Binary Tree

题目
Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.

The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation.

答案

public int widthOfBinaryTree(TreeNode root) {
        if(root == null) return 0;
        Queue<TreeNode> q = new LinkedList<TreeNode>();
        Map<TreeNode, Integer> map = new HashMap<>();
        int max = 1;
        
        q.offer(root);
        map.put(root, 0);
        while(q.size() != 0) {
            int curr_size = q.size();
            int leftmost = Integer.MAX_VALUE, rightmost = Integer.MIN_VALUE, idx;
            for(int i = 0; i < curr_size; i++) {
                TreeNode t = q.poll();
                if(t.left != null) {
                    q.offer(t.left);
                    idx = map.get(t) * 2 + 1;
                    map.put(t.left, idx);
                    leftmost = Math.min(leftmost, idx); 
                    rightmost = Math.max(rightmost, idx);
                    max = Math.max(max, rightmost - leftmost + 1);
                }
                if(t.right != null) {
                    q.offer(t.right);
                    idx = map.get(t) * 2 + 2;
                    map.put(t.right, idx);
                    leftmost = Math.min(leftmost, idx); 
                    rightmost = Math.max(rightmost, idx);
                    max = Math.max(max, rightmost - leftmost + 1);
                }
            }
            
        }
        return max;
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,168评论 0 10
  • Description Given a binary tree, write a function to get ...
    Juliiii阅读 3,535评论 0 0
  • 我认识老赵的情形现在想来就好像是一个笑话 ,高一新生见面的时候,我们班主任让我们每一个人轮流上黑板上写下自己的名...
    贾贾的胖子别跑阅读 3,496评论 0 0
  • 前阵子读到老舍先生笔下的春光,便憧憬着如他般躺在春光里,眼留着一条小缝,收取着天上轻松惬意的暖光。春晴果然值得等...
    张茜茜5665阅读 2,875评论 3 2
  • 老撒旦看她一眼,海儿柔笑呵呵的把手背到了后面。他伸手抓住渡鸦,然后朝天空一抛,让它飞走。 看见海儿柔不解的眼神,老...
    枢兰颜光阅读 1,657评论 0 0

友情链接更多精彩内容