看了左神视频求树的最大宽度不用哈希方法(不包含空节点)
int widthOfBinaryTree(TreeNode* root) {
std::queue<TreeNode*> queue;
queue.emplace(root);
TreeNode* cur_node = root;
TreeNode* next_node = nullptr;
int cur_level_nodes = 0;
int max = 0;
while(!queue.empty())
{
auto front_node = queue.front();
queue.pop();
if(nullptr != front_node->left)
{
queue.emplace(front_node->left);
next_node = front_node->left;
}
if(nullptr != front_node->right)
{
queue.emplace(front_node->right);
next_node = front_node->right;
}
cur_level_nodes++;
//遍历到当层的最后一个节点
if(front_node == cur_node)
{
max = std::max(max, cur_level_nodes);
cur_node = next_node;
next_node = nullptr;
cur_level_nodes = 0;
}
}
return max;
}