Eat Study Love

먹고 공부하고 사랑하라

Coding_Practice

Binary Tree Level Order Traversal[M,Tree,Breadth-First Search,Binary Tree]

eatplaylove 2024. 9. 2. 20:03

 

# 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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        ans = []
        self.dfs(root, ans, 0)
        return ans
    
    def dfs(self, node, ans, lv):
        if not node:
            return

        # 새 레벨이 추가될 때만 빈 리스트를 추가
        if len(ans) == lv:
            ans.append([])  
        
        ans[lv].append(node.val)

        self.dfs(node.left, ans, lv + 1)
        self.dfs(node.right, ans, lv + 1)

https://leetcode.com/problems/binary-tree-level-order-traversal/description/

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

 

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[9,20],[15,7]]

Example 2:

Input: root = [1]
Output: [[1]]

Example 3:

Input: root = []
Output: []

 

Constraints:

  • The number of nodes in the tree is in the range [0, 2000].
  • -1000 <= Node.val <= 1000

Binary Tree Traversal 문제이다.

 

1. C

아 malloc 하는게 너무나 구찮다..

GG

#include <stdio.h>
#include <stdlib.h>

// 이진 트리 노드 구조체 정의
struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};

int** levelOrder(struct TreeNode* root, int** columnSizes, int* returnSize) {
    if (root == NULL) {
        *returnSize = 0;
        return NULL;
    }

    // 메모리 초기화
    int maxNodes = 1000;  // 트리 노드의 최대 개수에 맞춰 배열 크기 지정
    struct TreeNode** queue = (struct TreeNode**)malloc(maxNodes * sizeof(struct TreeNode*));
    int** result = (int**)malloc(maxNodes * sizeof(int*));
    *columnSizes = (int*)malloc(maxNodes * sizeof(int));
    
    int front = 0, rear = 0;
    *returnSize = 0;

    // 루트 노드를 큐에 추가
    queue[rear++] = root;

    while (front < rear) {
        int levelSize = rear - front;  // 현재 레벨에 있는 노드의 수
        result[*returnSize] = (int*)malloc(levelSize * sizeof(int));
        (*columnSizes)[*returnSize] = levelSize;

        for (int i = 0; i < levelSize; i++) {
            struct TreeNode* node = queue[front++];
            result[*returnSize][i] = node->val;

            if (node->left != NULL) {
                queue[rear++] = node->left;
            }
            if (node->right != NULL) {
                queue[rear++] = node->right;
            }
        }
        (*returnSize)++;
    }

    free(queue);
    return result;
}

 

2. 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:
    vector<vector<int>> levelOrder(TreeNode* root) {
        queue<TreeNode*> q;
        vector<vector<int>> ans;
        if(!root) return ans;
        
        q.push(root);
        while(!q.empty()){
            int lv = q.size();
            vector<int> temp;

            for(int i=0;i<lv;i++){
                TreeNode* curr = q.front();
                q.pop();
                temp.push_back(curr->val);
                if(curr->left) q.push(curr->left);
                if(curr->right) q.push(curr->right);
            }
            ans.push_back(temp);
        }
        return ans;
    }
};


3. Python DFS로 재귀적인 풀이 가보자

# 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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
        ans = []
        self.dfs(root, ans, 0)
        return ans
    
    def dfs(self, node, ans, lv):
        if not node:
            return

        # 새 레벨이 추가될 때만 빈 리스트를 추가
        if len(ans) == lv:
            ans.append([])  
        
        ans[lv].append(node.val)

        self.dfs(node.left, ans, lv + 1)
        self.dfs(node.right, ans, lv + 1)