LC104二叉树的最大深度:
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
return self.getdepth(root)
def getdepth(self, node):
if not node:
return 0
leftdepth = self.getdepth(node.left)
rightdepth = self.getdepth(node.right)
depth = 1 + max(leftdepth, rightdepth)
return depth
LC 559.n叉树的最大深度:
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
最大深度用前序遍历,高度用后序遍历。而根节点的高度就是二叉树的最大深度。
LC111.二叉树的最小深度:
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
if not root.left and not root.right:
return 1
min_depth = float('inf')
if root.left:
min_depth = min(self.minDepth(root.left), min_depth) # 获得左子树的最小高度
if root.right:
min_depth = min(self.minDepth(root.right), min_depth) # 获得右子树的最小高度
return min_depth + 1
如果左子树为空,右子树不为空,说明最小深度是 1 + 右子树的深度。反之,右子树为空,左子树不为空,最小深度是 1 + 左子树的深度。 最后如果左右子树都不为空,返回左右子树深度最小值 + 1 。
LC222.完全二叉树的节点个数:
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
return self.getSumNode(root)
def getSumNode(self, cur):
if not cur:
return 0
left = self.getSumNode(cur.left)
right = self.getSumNode(cur.right)
sum = left + right + 1
return sum