104::二叉树的最大深度
深度是节点到根节点的距离。
高度是根节点到叶子节点的距离。
深度=高度
求最大深度,需要使用后序遍历,因为要不断“下基层”传递信息!
为了能够清楚地展示递归过程,乐乐画了一个递归图(累死我了),这样对递归的理解有帮助,每进一次递归,也就是每做一次套娃,就使用一种新颜色表示:
代码还是很简单的:
class Solution:
def getDepth(self,node):
if not node:
return 0
h_left=self.getDepth(node.left)
h_right=self.getDepth(node.right)
h=max(h_left,h_right)+1
return h
def maxDepth(self,root):
return self.getDepth(root)
做这个题的时候,还有个小插曲,运行一直报错,原来,我把if not node的时候,习惯性的返回了None,这次应该是int,因为要返回信息嘛,而不是单纯遍历了。
111:二叉树的最小深度
例如:求二叉树的最小深度,那直接把上一题的最大深度的代码中的max()改成min()不就行了嘛,这样做就没有考虑清楚最小高度的定义,也就是忽略了一种情况那就是:
例如,这种情况,如果直接改max为min,就会返回值为1(1节点对应的)而不是3(3节点对应的)。题目要求是返回,离根节点最近的叶子节点的最小高度。这个题还是要用后序遍历,只不过要加个判断:
def minDepth(self,root):
def getDepth(node):
if not node:
return 0
h_left=getDepth(node.left)
h_right=getDepth(node.right)
if not node.left and node.right:
return 1+h_right
elif node.left and not node.right:
return 1+h_left
else:
return 1+min(h_right,h_left)
return getDepth(root)
222:完全二叉树的节点个数
例如:觉得把它当作普通二叉树的解法,更好理解。
def countNodes(self,root):
def count(node):
if not node:
return 0
left_count=count(node.left)
right_count=count(node.right)
sum_count=left_count+right_count+1
return sum_count
return count(root)
利用完全二叉树的性质,进行求解:
def count(node):
if not node:
return 0
left=node.left
right=node.right
left_depth=0
right_depth=0
while(left):
left=left.left
left_depth=left_depth+1
while(right):
right=right.right
right_depth=right_depth+1
if right_depth==left_depth:
return (2<<left_depth)-1
return count(node.left)+count(node.right)+1
return count(root)
不过学会了一个写法:(2<<left_depth)用来求一个数的几次方,原本以为只有C++这么用,原来python也能这么用啊。
559:n叉树的最大深度
例如:n叉树需要遍历每个孩子,所以要用for循环,并且每次还要depth=0
再做记录depth+1
def maxDepth(self,root):
if not root:
return 0
depth=0
for i in range(len(root.children)):
depth=max(depth,self.maxDepth(root.children[i]))
return depth+1