给定一个二叉树,编写一个函数来获取这个树的最大宽度。树的宽度是所有层中的最大宽度。这个二叉树与满二叉树(full binary tree)结构相同,但一些节点为空。
每一层的宽度被定义为两个端点(该层最左和最右的非空节点,两端点间的null节点也计入长度)之间的长度。
示例 1:
输入:
1
/ \
3 2
/ \ \
5 3 9
输出: 4
解释: 最大值出现在树的第 3 层,宽度为 4 (5,3,null,9)。
示例 2:
输入:
1
/
3
/ \
5 3
输出: 2
解释: 最大值出现在树的第 3 层,宽度为 2 (5,3)。
示例 3:
输入:
1
/ \
3 2
/
5
输出: 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);
helper(h + 1,2*index,root->left,res,start);
helper(h + 1,2*index + 1,root->right,res,start);
}
};