给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7],
1.从上到下遍历二叉树的每一层。当遇到某个节点无子树时返回深度。
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
queue = [root]
count = 1
while queue:
# print(queue)
next_queue = []
for node in queue:
if not node.left and not node.right:
return count
if node.left:
next_queue.append(node.left)
if node.right:
next_queue.append(node.right)
queue = next_queue
count+=1
# print(count)
return count
2.递归
class Solution:
def minDepth(self, root: TreeNode) -> int:
if not root:
return 0
#单右枝
if not root.left and root.right:
return self.minDepth(root.right)+1
#单左枝
if not root.right and root.left:
return self.minDepth(root.left)+1
left = self.minDepth(root.left)+1
right = self.minDepth(root.right)+1
return min(left,right)
递归的话,需要考虑单只树的情况。
ps:对于这种自己调用自己的递归方法,小白新手也是经常把自己绕进去。但是,感觉看起来十分简洁,也不需要考虑很多限定条件的样子,就是把每一个点都当成一样的来看,都进行同样的计算。我的话觉得是不要想太多这个点之后会怎么样往下进行的逻辑,直接跳到下一个点去进行另一个重复运算。(实在不知道对不对,我也很头疼啊)有大佬能指教更好啦!