leetcode 662. 二叉树最大宽度

96 阅读1分钟

c++

class Solution {
public:
    typedef pair<TreeNode *, long long> PNI;
    int widthOfBinaryTree(TreeNode* root) {
        long long ans = 0;
        queue<PNI> que;
        que.push(PNI(root, 0));
        while (!que.empty()) {
            int n = que.size();
            long long l = que.front().second, r = que.front().second;
            for (int i = 0; i < n; i++) {
                PNI tmp = que.front();
                que.pop();
                r = max(r, tmp.second);
                if (tmp.first->left) que.push(PNI(tmp.first->left, (tmp.second - l) * 2));
                if (tmp.first->right) que.push(PNI(tmp.first->right, (tmp.second - l)* 2 + 1));
            }
            ans = max(ans, r - l + 1);
        }
        return ans;
    }
};

js

var widthOfBinaryTree = function(root) {
    var ans = 0;
    var que = [];
    que.push([root, 0]);
    while(que.length) {
        var n = que.length;
        var l = que[0][1], r = que[0][1];
        for (var i = 0; i < n; i++) {
            var tmp = que[0];
            que.shift();
            r = Math.max(r, tmp[1]);
            if (tmp[0].left) que.push([tmp[0].left, (tmp[1] - l) * 2]);
            if (tmp[0].right) que.push([tmp[0].right, (tmp[1] - l) * 2 + 1]);
        }
        ans = Math.max(ans, r - l + 1);
    }
    return ans;
};