- [二叉树]111. Minimum Depth of Binar
- 二叉树的最小、最大深度以及平衡二叉树
- [Tree]111. Minimum Depth of Bina
- leetcode:111. Minimum Depth of B
- 111. Minimum Depth of Binary Tre
- Q111 Minimum Depth of Binary Tre
- 111. Minimum Depth of Binary Tre
- Leetcode 111. Minimum Depth of B
- 111. Minimum Depth of Binary Tre
- 111. Minimum Depth of Binary Tre
- 分类:Tree
- 时间复杂度: O(n) 这种把树的节点都遍历一遍的情况时间复杂度为O(n)
- 空间复杂度: O(h) 树的节点的深度
111. Minimum Depth of Binary Tree
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.
代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minDepth(self, root: 'TreeNode') -> 'int':
if root==None:
return 0
return self.helper(root,1)
def helper(self,root,level):
level+=1
if root.left==None and root.right==None:
return level-1
elif root.left==None:
return self.helper(root.right,level)
elif root.right==None:
return self.helper(root.left,level)
else:
return min(self.helper(root.left,level),self.helper(root.right,level))
讨论:
1.虽然折腾了半天,但是这个代码是自己写的还是非常自豪滴!
网友评论