给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最小深度 2.
一、思路
这里的重点是要找根到叶的最短距离,因此必须一直往下寻找,直到遇到叶节点
可以采用后序遍历,找出左右子树的最小深度,取其中较小的那个
C++代码
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root)
return 0;
return findMinDepth(root, 0);
}
int findMinDepth(TreeNode* root,int pre_depth) {
int cur_depth = pre_depth + 1;
if (root->left == NULL && root->right == NULL)
return cur_depth;
int left_depth = INT32_MAX, right_depth = INT32_MAX;
if (root->left)
left_depth = findMinDepth(root->left, cur_depth);
if (root->right)
right_depth = findMinDepth(root->right, cur_depth);
int min_depth = min(left_depth, right_depth);
return min_depth;
}
int min(int a, int b) {
return (a > b) ? b : a;
}
};
执行效率: