原题链接
标签 :二叉树 BFS
解题思路:BFS广度优先 + 队列
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode(int x) : val(x), left(NULL), right(NULL) {}* };*/
class Solution {
public:int widthOfBinaryTree(TreeNode* root) {if (!root) return 0;queue<pair<TreeNode*, unsigned long long>> q;int ans = 1;q.push({root, 1});while (!q.empty()) {int sz = q.size();ans = max(int(q.back().second - q.front().second + 1), ans);for (int i=0; i < sz; i++) {TreeNode *node = q.front().first;unsigned long long pos = q.front().second;q.pop();if (node->left) q.push({node->left, 2 * pos});if (node->right) q.push({node->right, 2 * pos + 1});}}return ans;}
};