1、二叉树的最大深度(即二叉树的高度)
二叉树的高度:根节点最高 遍历方法:后序遍历,左右中
二叉树的深度:根节点最小 遍历方法:前序遍历,中左右
因此实际采用的是后序遍历方法。
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
return self.getdepth(root)
def getdepth(self,node):
if not node:
return 0
left = self.getdepth(node.left)
right = self.getdepth(node.right)
depth = 1 + max(left,right)
return depth
2、n叉树的最大深度:唯一区别在于
for child in root.children:
3、二叉树的最小深度
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
return self.get_depth(root)
def get_depth(self,node):
if not node:
return 0
left_depth = self.get_depth(node.left)
right_depth = self.get_depth(node.right)
if left_depth == 0 and right_depth >0:
result = right_depth + 1
elif right_depth == 0 and left_depth >0:
result = left_depth +1
else: result = min(left_depth,right_depth)+1
return result
4、完全二叉树节点数
普通的遍历方法:
时间复杂度O(n),使用递归方法
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
return self.get_num(root)
def get_num(self,node):
if not node:
return 0
left = self.get_num(node.left)
right = self.get_num(node.right)
mid = left+right +1
return mid
利用完全二叉树的特性,判断其子树是否为一个满二叉树,如果是,那么其节点个数为2** k - 1
如何判断是否为满二叉树,利用其完全二叉树的特性:因此仅需判断左子树和右子树的长度是是否相等。
注意点:left_depth的初始长度为1
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
left = root.left
right = root.right
left_depth = 1
right_depth = 1
while left:
left = left.left
left_depth += 1
while right:
right = right.right
right_depth += 1
if right_depth==left_depth:
return 2 ** left_depth - 1
return self.countNodes(root.left)+self.countNodes(root.right)+ 1