题目:
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:
Given binary tree [3,9,20,null,null,15,7]
,
3 / \ 9 20 / \ 15 7
return its minimum depth = 2.
当左右子树高度仅有一个为0,说明该节点不是叶子结点,树的高度为左右子树高度和加1;
否则,左右子树高度都为0或左右子树高度都不为0,则取高度小的子树加1;这样能保证取得的最小高度的节点为叶子节点
代码如下:
/**
* 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 == NULL)
return 0;
int leftH = minDepth(root->left);
int rightH = minDepth(root->right);
if(leftH == 0 || rightH == 0)
return leftH + rightH + 1;
return min(leftH,rightH) + 1;
}
};