559 N叉树的最大深度,需要定义一个depth = 0,和每一个子节点去比较,存下来最大值。
class solution:
def maxdepth(self, root: 'node') -> int:
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
104 二叉树的最大深度,不需要这个depth, 因为每次只要比较2个值。
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
本质是,你一次比较两个值,max即可。一次比较多个,就要两个两个比较,而且要有一个位置存每次找到的最大值。
222 完全二叉树的节点个数
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
left = root.left
right = root.right
leftDepth = 0
rightDepth = 0
while left:
left = left.left
leftDepth += 1
while right:
right = right.right
rightDepth += 1
if leftDepth == rightDepth:
return (2 << leftDepth) - 1
return self.countNodes(root.left) + self.countNodes(root.right) + 1
也是递归,把最后的叶子节点也当成一个完全二叉树,作为递归的最小单元。
递归三要素:
- 确定递归函数的参数和返回值:参数就是传入树的根节点,返回就返回以该节点为根节点二叉树的节点数量,所以返回值为int类型。
- 确定终止条件:如果为空节点的话,就返回0,表示节点数为0。
- 确定单层递归的逻辑:先求它的左子树的节点数量,再求右子树的节点数量,最后取总和再加一 (加1是因为算上当前中间节点)就是目前节点为根节点的节点数量。