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.
复制代码
- (int)minimumDepth:(DSTreeNode *)root
{
//1
if (root == nil) {
return 0;
}
//2
if (root.leftChild == nil) {
return [self minimumDepth:root.rightChild]+1;
}
//3
if (root.rightChild == nil) {
return [self minimumDepth:root.leftChild]+1;
}
//4
return MIN([self minimumDepth:root.leftChild], [self minimumDepth:root.rightChild])+1;
}
复制代码
遍历二叉树的每一个节点,若是当前节点是叶子节点,则返回1。node
若是不是叶子节点,且左子树为null,而后递归右子树。git
若是不是叶子节点且右子树为null,而后递归左子树。github
若是不是叶子节点,且左右子树不为null那么取递归后二者最小值。bash
因为遍历树的每一个节点,所以时间复杂度是O(n)。ui
固然还有其余不错的思路好比用层级遍历的方法,返回第一个遇到叶子节点的深度。spa