Eat Study Love

먹고 공부하고 사랑하라

Coding_Practice

Maximum Width of Binary Tree[M,Tree,Depth-First Search,Breadth-First Search,Binary Tree]

eatplaylove 2024. 8. 22. 15:41

https://leetcode.com/problems/maximum-width-of-binary-tree/description/

Given the root of a binary tree, return the maximum width of the given tree.

The maximum width of a tree is the maximum width among all levels.

The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes), where the null nodes between the end-nodes that would be present in a complete binary tree extending down to that level are also counted into the length calculation.

It is guaranteed that the answer will in the range of a 32-bit signed integer.

 

Example 1:

Input: root = [1,3,2,5,3,null,9]
Output: 4
Explanation: The maximum width exists in the third level with length 4 (5,3,null,9).

Example 2:

Input: root = [1,3,2,5,null,null,9,6,null,7]
Output: 7
Explanation: The maximum width exists in the fourth level with length 7 (6,null,null,null,null,null,7).

Example 3:

Input: root = [1,3,2,5]
Output: 2
Explanation: The maximum width exists in the second level with length 2 (3,2).

 

Constraints:

  • The number of nodes in the tree is in the range [1, 3000].
  • -100 <= Node.val <= 100

감이 안 잡히게 어렵다.

 

결국 GPT 도움..

골자는 Node마다 index를 부여해서 max width를 tracking 하는 것이고,

Level 마다 BST를 사용하는 건 맞았음.

 

1. C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int widthOfBinaryTree(TreeNode* root) {
        if(!root) return 0;

        queue<pair<TreeNode*, int>> q;
        q.push({root,1});
        int maxWidth = 0;
        
        while(!q.empty()){
            int lvsize = q.size();
            int first = q.front().second;
            int last = q.back().second;

            maxWidth = max(maxWidth, last-first+1);

            for(int i=0; i<lvsize; i++){
                TreeNode* node = q.front().first;
                int idx = q.front().second;
                q.pop();
                // Key Point!
                if(node->left) q.push({node->left,idx*2});
                if(node->right) q.push({node->right,1+idx*2});
            }
        }
        return maxWidth;
    }
};

 

leetcode가 미쳐서 overflow를 방지하라는데,, overflow까지 고려하면 아래와 같다.

int widthOfBinaryTree(TreeNode* root) {
    if (root == nullptr) return 0;

    queue<pair<TreeNode*, long long>> q; // 노드와 그 인덱스를 저장하는 큐
    q.push({root, 1});
    int maxWidth = 0;

    while (!q.empty()) {
        int levelSize = q.size();
        long long minIndex = q.front().second;
        long long first, last;

        for (int i = 0; i < levelSize; i++) {
            TreeNode* node = q.front().first;
            long long idx = q.front().second - minIndex; // 오버플로우 방지를 위해 인덱스를 재조정
            q.pop();

            if (i == 0) first = idx;
            if (i == levelSize - 1) last = idx;

            if (node->left) q.push({node->left, 2 * idx});
            if (node->right) q.push({node->right, 2 * idx + 1});
        }

        maxWidth = max(maxWidth, static_cast<int>(last - first + 1));
    }

    return maxWidth;
}

 

2. Python

위 C++과 같은 메커니즘

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        if not root : return 0
        q = deque()
        q.append([root,1]) # idx of root is 1
        ans = 0
        while q :
            size = len(q)
            first = q[0][1]
            last = q[-1][1]
            ans = max(ans,last-first+1)
            for i in range(size):
                curr = q.popleft()
                idx = curr[1]
                if curr[0].left :
                    q.append([curr[0].left,idx*2])
                if curr[0].right :
                    q.append([curr[0].right,1+idx*2]) 
        return ans

 

3.

Queue가 없는 C.. 얘가 난해하다..!

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int widthOfBinaryTree(struct TreeNode* root){
    if(!root) return 0;

    struct TreeNode* q[10000];
    int idx[10000];
    int front = 0, rear = 0;

    q[rear] = root;
    idx[rear++] = 1;
    int ans = 0;

    while(front < rear){
        int lvsize = rear - front;
        int first = idx[front];
        int last = idx[rear-1];
        int w = last - first + 1;
        if(w > ans) ans = w;

        for(int i=0;i<lvsize;i++){
            struct TreeNode* node = q[front];
            int idxnum = idx[front++];

            if(node->left != NULL){
                q[rear] = node->left;
                idx[rear++] = 2*idxnum;
            }
            if(node->right != NULL){
                q[rear] = node->right;
                idx[rear++] = 1+2*idxnum;
            }
        }
    }
    return ans;
}