问题描述:
Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null.
The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null
nodes between the end-nodes are also counted into the length calculation.
示例:
Input: 1 / \ 3 2 / \ \ 5 3 9 Output: 4 Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9).
Input: 1 / 3 / \ 5 3 Output: 2 Explanation: The maximum width existing in the third level with the length 2 (5,3).
Input: 1 / \ 3 2 / 5 Output: 2 Explanation: The maximum width existing in the second level with the length 2 (3,2).
Input: 1 / \ 3 2 / \ 5 9 / \ 6 7 Output: 8 Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7).
问题分析:
题目主要考查节点编号问题,对于一个左子节点,其编号为父节点编号的两倍,而右子节点编号为父节点编号两倍加1.
最终遍历每层找到最左最右节点编号,取其中最大的差值加1即为答案。
过程详见代码:
/**
* 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 == nullptr) return 0;
int res = 0;
vector<pair<int, int>> val;
val.emplace_back(pair<int, int>(1, 1));
dfs(root->left, val, 1, 1, 0);
dfs(root->right, val, 1, 1, 1);
for (auto v : val)
{
int t = v.second - v.first + 1;
if (t > res) res = t;
}
return res;
}
void dfs(TreeNode* root, vector<pair<int, int>>& val, int depth, int parent, int dirt)
{
if (root == nullptr) return;
if (val.size() <= depth) val.emplace_back(pair<int, int>(parent * 2 + dirt, parent * 2 + dirt));
else val[depth].second = parent * 2 + dirt;
dfs(root->left, val, depth + 1, parent * 2 + dirt, 0);
dfs(root->right, val, depth + 1, parent * 2 + dirt, 1);
}
};