637. Average of Levels in Binary Tree
来源:互联网 发布:触摸屏 手势软件 编辑:程序博客网 时间:2024/06/04 17:53
/** * 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: vector<double> averageOfLevels(TreeNode* root) { vector<double> res; double count=0, sum=0; queue<TreeNode*> q; q.push(root); q.push(NULL); while(!q.empty()){ TreeNode* u=q.front(); q.pop(); if(u==NULL){ res.push_back(sum/count); sum=count=0; if(!q.empty()) q.push(NULL); } else{ sum+=u->val; ++count; if(u->left) q.push(u->left); if(u->right) q.push(u->right); } } return res; }};
使用队列(FIFO),进行宽度优先搜索(bfs)
主要需要解决的问题是,如何判断一层已经结束了。这个题解我觉得比较巧妙,使用NULL来隔离每一层。
第一层只有一个根节点,所以队列中push进root之后,立刻push进一个nullptr。
1. 获取队列头部的根节点1之后,弹出根节点,push进它的左右子树2,3。
2. 获取队列头部的nullptr,第一层结束,push进一个新的nullptr,当前的队列为2->3->NULL
3. 获取队列头部的结点2,push进它的左右子树4,5,当前的队列为3->NULL->4->5
4. 获取队列头部结点3,push进它的左右子树6,7,当前队列为NULL->4->5->6->7
以此类推。也就是说遍历完上一层的时候就已经把下一层的结点全部放入队列了,这时候加一个NULL标记。
阅读全文
0 0
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- 637. Average of Levels in Binary Tree
- [Leetcode] Binary tree-- 637. Average of Levels in Binary Tree
- 进程间通信之匿名管道
- Spring MVC
- utf-8及转换
- DevStack环境搭建
- C++ 软件设计思想
- 637. Average of Levels in Binary Tree
- appium创建session失败:selenium.common.exceptions.WebDriverException: Message: A new session could not be
- ES基础概念
- Ubuntu系统源码搭建cms、WordPress(Apache+php+mysql)
- Android数据库高手秘籍(零)——前言
- 在.net中添加Newtonsoft.Json.dll引用
- SSL P2690 fbi序列
- android Studio导入source文件
- spring浅解