Coding test/Leet Code

[LeetCode C++] 104. Maximum Depth of Binary Tree

HEY__ 2021. 9. 30. 20:07
728x90

⭐️ 난이도

Easy


⭐️ 문제

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

 

Maximum Depth of Binary Tree - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

이진 트리의 root가 주어졌을 때, 최대 깊이(depth)를 구하라.

 


⭐️ Follow-up

X


⭐️ Idea flow

 

최대 depth를 구하기 위해서는 사용할 수 있는 두 가지 방법이 있다.

BFS와 DFS인데 root 노드에서 시작해서 한 단계 진행 할 때마다 depth를 1씩 증가시키면서 최대 값을 갱신하면 된다.

 

이번 구현은 DFS와 BFS 모두 시도 해보았다.

DFS가 시간적, 공간적 측면에서 BFS보다 더 좋게 나왔다.

 

 

 

 

 

첫 번째: DFS

두 번째: BFS

 

 


⭐️ Code

/**
 * 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) {}
 * };
 */
///////////////// DFS ver
class Solution { 
public:
    int result = 0;
    int maxDepth(TreeNode* root, int depth = 1) {
        if(root == nullptr) return 0;
        
        result = max(result, depth);
        if(root->left){
            maxDepth(root->left, depth + 1);
        }
        if(root->right){
            maxDepth(root->right, depth + 1);
        }
        return result;
    }
};

///////////////// BFS ver
class Solution { 
public:
  
    int maxDepth(TreeNode* root) {
        if(root == nullptr){
            return 0;
        }
        
        int result = 0;
        queue<pair<TreeNode*, int>> q;
        q.push({root, 1});
        
        while(!q.empty()){
            TreeNode* cur = q.front().first;
            int cur_depth = q.front().second;
            q.pop();
            
            result = max(result, cur_depth);

            if(cur->left)
                q.push({cur->left, cur_depth + 1});
            if(cur->right)
                q.push({cur->right, cur_depth + 1});
        }  
        return result;
    }
};

 

 


 

 

 

 

728x90