代码随想录算法训练营|104.二叉树的最大深度; 111.二叉树的最小深度;101. 对称二叉树
104.二叉树的最大深度
题目链接: 104.二叉树的最大深度
文档讲解: 代码随想录
题目难度:简单
思路:递归法
时间复杂度:O(n);空间复杂度:O(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 depth(self, current):
# 前序遍历
if not current:
return 0
else:
depth = 1
leftdepth = self.depth(current.left)
rightdepth = self.depth(current.right)
return depth + max(leftdepth, rightdepth)
def maxDepth(self, root: Optional[TreeNode]) -> int:
return self.depth(root)
111.二叉树的最小深度
题目链接: 111.二叉树的最小深度
文档讲解: 代码随想录
题目难度:简单
思路:递归+前序遍历
时间复杂度:O(n);空间复杂度:O(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 depth(self, current):
if not current:
return 0
else:
leftdepth = self.depth(current.left)
rightdepth = self.depth(current.right)
if current.left and current.right == None:
# 该节点不是叶子节点
return 1 + leftdepth
elif current.right and current.left == None:
# 该节点不是叶子节点
return 1 + rightdepth
else:
return 1+min(leftdepth, rightdepth)
# 最小深度是从根节点到最近叶子节点的最短路径上的节点数量
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
else:
return self.depth(root)
222.完全二叉树的节点个数
题目链接: 222.完全二叉树的节点个数
文档讲解: 代码随想录
题目难度:简单
思路:递归+前序遍历
时间复杂度:O(n);空间复杂度:O(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 getNodesNum(self, current):
# 结束条件
if not current:
return 0
else:
left = self.getNodesNum(current.left)
right = self.getNodesNum(current.right)
return left + right + 1
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
else:
return self.getNodesNum(root)