遍历顺序:
后续遍历
核心逻辑:
使用max函数,取左右子树最大值递归‘
特殊点:
有返回值
class Solution:
def maxdepth(self, root: treenode) -> int:
return self.getdepth(root)
def getdepth(self, node):
if not node:
return 0
leftheight = self.getdepth(node.left) #左
rightheight = self.getdepth(node.right) #右
height = 1 + max(leftheight, rightheight) #中
return height
题目二
遍历顺序:
后续遍历
核心逻辑:
使用min函数,取左右子树最小值递归‘
特殊点:
对于左子树为空、右子树存在
对于右子树为空、左子树存在的特殊情况进行处理,
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
left_h=self.minDepth(root.left)
right_h=self.minDepth(root.right)
if root.left is None and root.right is not None:
return 1+ right_h
if root.right is None and root.left is not None:
return 1+left_h
return min(left_h,right_h)+1
第三题
遍历顺序:
后续遍历
核心逻辑:
对每个结点来说,判断其是不是构成一个满二叉树
判断满二叉树:一直向左遍历的层数====一直向右遍历的层数
特殊点:
设立4个遍历
left,leftdepth,
right,rightdepth
判断每个节点是不是满二叉树
class Solution(object):
def countNodes(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
left_h=1
right_h=1
left=root.left
right=root.right
while left:
left_h+=1
left=left.left
while right:
right_h+=1
right=right.right
if left_h==right_h:
return (2 ** left_h)-1
ln=self.countNodes(root.left) #左
rn=self.countNodes(root.right) #右
return ln+rn+1 #中