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