最小深さを調べるために、バイナリツリーを考えます。
最小深さは、リーフノードに最も近いルートノードから最短パス内のノードの数です。
説明:リーフノードは、ノードが子ノードを持たないです。
例:
与えられたバイナリツリー[3,9,20、NULL、NULL、15,7]、
3
/ \
920
/ \
157件
の最小深さ2に戻ります。
BFS:
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
queue<TreeNode*> q{{root}};
int level = 0;
while(!q.empty())
{
level++;
for(int i = q.size();i > 0;i--)
{
TreeNode* t = q.front();q.pop();
if(!t->left && !t->right)
return level;
if(t->left) q.push(t->left);
if(t->right) q.push(t->right);
}
}
return -1;
}
};
再帰:
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root) return 0;
if (!root->left) return 1 + minDepth(root->right);
if (!root->right) return 1 + minDepth(root->left);
return 1 + min(minDepth(root->left), minDepth(root->right));
}
};
DFS:スタック
class Solution {
public:
int minDepth(TreeNode* root) {
if(!root) return 0;
stack<pair<TreeNode*,int>> ss;
ss.push(make_pair(root,1));
int res = INT_MAX;
while(!ss.empty())
{
TreeNode * t = ss.top().first;
int level = ss.top().second;
ss.pop();
if(!t->left && !t->right)
{
res = min(level,res);
}
if(t->left)
ss.push(make_pair(t->left,level + 1));
if(t->right)
ss.push(make_pair(t->right,level + 1));
}
return res;
}
};