111. Minimum Depth of Binary Tree (最小树深度\bfs)
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.
# 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 import queue class Solution: def minDepth(self, root: Optional[TreeNode]) -> int: if root== None: return 0 if root.left== None and root.right ==None: return 1 elif root.left and root.right: return 1 + min(self.minDepth(root.left), self.minDepth(root.right)) elif root.left: return 1 + self.minDepth(root.left) elif root.right: return 1+self.minDepth(root.right) return 0
/** * 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: int minDepth(TreeNode* root) { if (root==nullptr) return 0; queue<TreeNode*> q; q.push(root); int depth = 1; while(!q.empty()) { int sz = q.size(); for(int i = 0; i < sz;i++) { TreeNode* cur = q.front(); q.pop(); if (cur->left == nullptr && cur->right == nullptr) { return depth; } if (cur->left != nullptr) q.push(cur->left); if (cur->right!= nullptr) q.push(cur->right); } depth++; } return depth; } };
1 class Solution { 2 public: 3 4 int minDepth(TreeNode* root) { 5 if (root == nullptr) return 0; 6 if (root->left != nullptr && root->right != nullptr) { 7 return 1 + min(minDepth(root->left),minDepth(root->right)); 8 } else if (root->left != nullptr && root->right == nullptr) { 9 return 1 + minDepth(root->left); 10 } else if (root->left == nullptr && root->right != nullptr) { 11 return 1 + minDepth(root->right); 12 } 13 return 1; 14 } 15 };