[leetcode]662. Maximum Width of Binary Tree
Analysis
Happy girls day—— [每天刷题并不难0.0]
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.
Explanation:
Solved by DFS
Implement
/**
* 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) {
return DFS(root, 0, 1);
}
int DFS(TreeNode* root, int level, unsigned int idx){
if(root == NULL)
return 0;
if(lev.size() == level)
lev.push_back({idx, idx});
else
lev[level].second = idx;
return max({lev[level].second-lev[level].first+1, DFS(root->left, level+1, idx*2), DFS(root->right, level+1, idx*2+1)});
}
private:
vector<pair<int, int>> lev;
};