LeetCode111. Minimum Depth of Binary Tree
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.
由题意,要寻找该二叉树的最小深度值,即要找到最近的那个叶子节点。假若用DFS,要不停搜寻、排错,而用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 == NULL) return 0;int left_minDepth = minDepth(root->left);int right_minDepth = minDepth(root->right);if (left_minDepth == 0) return right_minDepth + 1;if (right_minDepth == 0) return left_minDepth + 1;return left_minDepth > right_minDepth?right_minDepth + 1:left_minDepth + 1;}
};