LeetCode #104 #111 2018-08-05
2018-08-05 本文已影响0人
40巨盗
104. Maximum Depth of Binary Tree
https://leetcode.com/problems/maximum-depth-of-binary-tree/description/
一般都是用递归实现。思路很简单,只需要对走到空结点返回0,然后其他依次按层递增,取左右子树中大的深度加1作为自己的深度即可。
代码如下:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
非递归解法一般采用层序遍历(相当于图的BFS),因为如果使用其他遍历方式也需要同样的复杂度O(n). 层序遍历理解上直观一些,维护到最后的level便是树的深度。
代码如下:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
queue = [root]
cur_num = 1
nxt_num = 0
level = 0
while queue:
node = queue.pop()
cur_num -= 1
if node.left:
queue.insert(0, node.left)
nxt_num += 1
if node.right:
queue.insert(0, node.right)
nxt_num += 1
if cur_num == 0:
cur_num = nxt_num
nxt_num = 0
level += 1
return level
111. Minimum Depth of Binary Tree
https://leetcode.com/problems/minimum-depth-of-binary-tree/description/
这道题因为是判断最小深度,所以必须增加一个叶子的判断(因为如果一个节点如果只有左子树或者右子树,我们不能取它左右子树中小的作为深度,因为那样会是0,我们只有在叶子节点才能判断深度,而在求最大深度的时候,因为一定会取大的那个,所以不会有这个问题)。这道题同样是递归和非递归的解法,递归解法比较常规的思路,比Maximum Depth of Binary Tree多加一个左右子树的判断。
代码如下:
# 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):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
if not root.left:
return self.minDepth(root.right) + 1
if not root.right:
return self.minDepth(root.left) + 1
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
非递归解法同样采用层序遍历(相当于图的BFS),只是在检测到第一个叶子的时候就可以返回了。
代码如下:
# 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):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
queue = [root]
cur_num = 1
nxt_num = 0
level = 1
while queue:
node = queue.pop()
cur_num -= 1
if not node.left and not node.right:
break
if node.left:
queue.insert(0, node.left)
nxt_num += 1
if node.right:
queue.insert(0, node.right)
nxt_num += 1
if cur_num == 0:
cur_num = nxt_num
nxt_num = 0
level += 1
return level