ice rabbit programming

[LeetCode] Minimum Depth of Binary Tree 본문

PS/LeetCode

[LeetCode] Minimum Depth of Binary Tree

판교토끼 2020. 4. 20. 23:08

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

 

Minimum 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

이진 트리에서 최소 깊이를 가진 leaf node의 depth를 구하는 문제이다. 기본적인 BFS 문제라고 생각한다.

/**
 * 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 minDepth(TreeNode* root) {
        if(root==nullptr)
            return 0;
        int index=0;
        queue<TreeNode*> q;
        vector<int> d;
        d.push_back(1);
        q.push(root);
        while(!q.empty()) {
            TreeNode* temp = q.front();
            q.pop();
            if(temp->right==nullptr && temp->left==nullptr)
                return d[index];
            if(temp->right!=nullptr) {
                q.push(temp->right);
                d.push_back(d[index]+1);
            }
            if(temp->left!=nullptr) {
                q.push(temp->left);
                d.push_back(d[index]+1);
            }
            index++;
        }
        return d[index];
    }
};