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.
Note: A leaf is a node with no children.
Example 1:
Input: root = [3,9,20,null,null,15,7] Output: 2
Example 2:
Input: root = [2,null,3,null,4,null,5,null,6] Output: 5
Constraints:
- The number of nodes in the tree is in the range
[0, 105]
. -1000 <= Node.val <= 1000
题目大意:求二叉树的最小深度。
难度:简单题
方法一:深度优先搜索(DFS)
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 int minDepth(TreeNode* root) { 15 if (root == nullptr) return 0; 16 int left = minDepth(root->left); 17 int right = minDepth(root->right); 18 return (left == 0 || right == 0) ? left + right + 1 : min(left, right) + 1; 19 } 20 };
方法二:广度优先搜索(BFS)
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode() : val(0), left(nullptr), right(nullptr) {} 8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} 9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} 10 * }; 11 */ 12 class Solution { 13 public: 14 int minDepth(TreeNode *root) { 15 queue<TreeNode*> q; 16 TreeNode *temp; 17 if (root == nullptr) return 0; 18 q.push(root); 19 bool flag = false; 20 int d = 1; 21 while (!q.empty()) { 22 int len = q.size(); 23 for (int i = 0; i < len; ++i) { 24 temp = q.front(); 25 q.pop(); 26 if ((temp->left == nullptr) && (temp->right == nullptr)) { 27 flag = true; 28 break; 29 } 30 if (temp->left) q.push(temp->left); 31 if (temp->right) q.push(temp->right); 32 } 33 if (flag) { 34 break; 35 } 36 ++d; 37 } 38 return d; 39 } 40 };