Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
给你一个二叉树,找到它的最浅深度
这个题目我采取的是用深度遍历的方法,把每次得到的深度保存起来即depth,如果depth小于len,我们就令len为depth,遍历整个二叉树
后得到的len就是最浅深度
/**
* 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:
void depthFirstSearch(TreeNode* root, int depth)
{
if (root == NULL)return;
if (root->left)
{
depthFirstSearch(root->left, ++depth);
depthFirstSearch(root->right, depth);
}
else
{
if (root->right)
{
depthFirstSearch(root->right, ++depth);
}
else
{
if (++depth < len)len = depth;
}
}
}
int minDepth(TreeNode* root) {
int depth = 0;
depthFirstSearch(root, depth);
if(len==INT32_MAX)
return 0;
else
return len;
}
private:
int len = INT32_MAX;
};
浙公网安备 33010602011771号