Leetcode problem solution-662. Maximum width of binary tree

Topic link

Title description:

Given a binary tree, write a function to get the maximum width of the tree. The width of the tree is the maximum width in all layers. This binary tree has the same structure as a full binary tree, but some nodes are empty.

The width of each layer is defined as the length between two endpoints (the leftmost and rightmost non-empty nodes of the layer, and the null nodes between the two ends are also included in the length).

Example 1:
Insert picture description here
Example 2:
Insert picture description here
Example 3:
Insert picture description here
Example 4:
Insert picture description here


BFS

  The title suggests our 满二叉树structure, so let us review the structural characteristics of a full binary tree (a special case of a full binary tree)? Considering the subject, we are required to ask for the width of the tree instead of the depth, and naturally thought that it might be a level traversal, which is BFS. So how to record the width of each layer? The simple is level + 1obviously not enough to solve the problem. At this time, it is necessary to consider the numerical relationship between the parent node and the left and right child node indexes in the complete binary tree, ie 父节点索引为i,左子结点索引为2 * i,右子结点索引为2 * i + 1. Draw a picture and think about it, 当前层的最右端索引 - 当前层的最左端索引 + 1that is, the width of the current layer, and the rest will keep maxlooking for the maximum width. Of course, you can also add a list或vectorspecial record of the leftmost index of each layer (this is used level).


Code

class Solution {
    
    
public:
    int widthOfBinaryTree(TreeNode* root) {
    
    
        if(!root)
            return 0;
        
        unsigned long long width = 0;
        queue< pair<TreeNode*,unsigned long long> > q;
        q.push(make_pair(root,1));
        while(!q.empty()){
    
    
            int size = q.size();
            unsigned long long l, r;
            for(int i = 0; i < size; i++){
    
    
                TreeNode* node = q.front().first;
                unsigned long long pos = q.front().second;
                q.pop();

                if(i == 0)
                    l = pos;
                if(i == size - 1)
                    r = pos;

                if(node->left)
                    q.push(make_pair(node->left,pos * 2));
                if(node->right)
                    q.push(make_pair(node->right,pos * 2 + 1));
            }
            width = max(width, r - l + 1);
        }

        return width;
    }
};

DFS

  Under normal circumstances, we use DFS to find the height of the tree. Can this question be used? The answer is yes! The last sentence just now reminded us. In fact, the road is ideal, but it is different from just using the queue for each layer to make a settlement. Because of the characteristics of recursion, we need to record the leftmost index of each layer, and then levellocate the layer of the current node and compare it with the leftmost index of the layer. 相减并加1, Keep maxgetting the current maximum width.
  So how does the computer know whether the current node is the leftmost node of the current layer? You may want to traverse the framework in order, and proceed when we pass the node for the first time visit, which provides a prerequisite for us to solve this requirement. We set a container recordLevelthat records the index of the leftmost endpoint . Obviously, the number of layers sizeis equal to the size of the container. After the node, it is judged whether the current layer is the >size of the container. If it is greater than that, it is obviously the first time to reach this level. If you traverse first 根左右, you can conclude that this is the leftmost node of the current layer, just record it. The operation of the current node is to calculate the maximum width, and the rest is handed over to recursion~


Code

class Solution {
    
    
public:
    int widthOfBinaryTree(TreeNode* root) {
    
    
        if(!root)
            return 0;
        
        helper(root, 1, 1);
        return width;
    }

private:
    unsigned long long width = 0;
    vector<unsigned long long> recordLevel;
    void helper(TreeNode* root, unsigned long long pos, int level){
    
    
        if(!root)
            return;

        if(level > recordLevel.size())
            recordLevel.push_back(pos);
        width = max(width, pos - recordLevel[level - 1] + 1);
        if(root->left)
            helper(root->left, pos * 2, level + 1);
        if(root->right)
            helper(root->right, pos * 2 + 1, level + 1);

        return;
    }
};

About test cases

  If we use intor long longrecord the maximum width widthand index pos, whether it is DFS or BFS, we are likely to fall into the test case 107, don’t ask how I know it~ Integer overflow

Line 35: Char 54: runtime error: signed integer overflow: 2147483647 * 2 cannot be represented in type 'int' (solution.cpp)

  How to solve it, a relatively simple way is to set the variable type of width and index unsigned long longto pass.


If there are mistakes or not rigorous, please correct me, thank you very much.
My blog: http://breadhunter.gitee.io

Guess you like

Origin blog.csdn.net/weixin_40807714/article/details/105196135