网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
输出: 2
解释: 最大值出现在树的第 2 层,宽度为 2 (3,2)。
示例 4:
输入:
1
/ \
3 2
/ \
5 9
/ \
6 7
输出: 8
解释: 最大值出现在树的第 4 层,宽度为 8 (6,null,null,null,null,null,null,7)。
注意: 答案在32位有符号整数的表示范围内。
解:首先使用树的层序遍历,记录好最左边节点和最右边节点的位置即可,该题因为溢出的问题,所有用double防止溢出。
/**
* 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;
double res = 0;
queue<pair<TreeNode*,double>> q;
q.push(make_pair(root,1));
while(!q.empty())
{
double left = q.front().second,right = left,n = q.size();
for(int i = 0;i < n;i++)
{
TreeNode* t = q.front().first;
right = q.front().second;q.pop();
if(t->left) q.push(make_pair(t->left,2*right));
if(t->right) q.push(make_pair(t->right,2*right + 1));
}
res = max(res,right - left + 1);
}
return int(res);
}
};
DFS:
/**
* 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) {
int M = 1e7;
double res = 0;
vector<double> start;
helper(0,1,root,res,start);
return res;
}
void helper(double h,double index,TreeNode* root,double &res,vector<double> &start)
{
if(!root) return;
if(h >= start.size()) start.push_back(index);
res = max(res,index - start[h] + 1);
![img](https://img-blog.csdnimg.cn/img_convert/bfc979b5def8a7a2ca95effdf734c6c7.png)
![img](https://img-blog.csdnimg.cn/img_convert/12e302a549d9f6cb4ef8dbecb8681772.png)
**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**
**[需要这份系统化的资料的朋友,可以添加戳这里获取](https://bbs.csdn.net/topics/618658159)**
**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**
159)**
**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**