226.翻转二叉树
101. 对称二叉树
104.二叉树的最大深度
111.二叉树的最小深度
222.完全二叉树的节点个数
110.平衡二叉树
102. 二叉树的所有路径
226.翻转二叉树
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return
tmp = root.left
root.left = root.right
root.right = tmp
self.invertTree(root.left)
self.invertTree(root.right)
return root
101. 对称二叉树
class Solution:
def left_right(self, left, right):
if (not left and right) or (not right and left):
return False
if not left and not right:
return True
if left.val != right.val:
return False
if self.left_right(left.left, right.right) and self.left_right(left.right, right.left):
return True
return False
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if not root.left and not root.right:
return True
if not root.left or not root.right:
return False
return self.left_right(root.left, root.right)
104.二叉树的最大深度
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
res_mid = []
def bfs(node, level, res_mid):
if not node:
return
if len(res_mid) == level:
res_mid.append([])
res_mid[level].append(node.val)
bfs(node.left, level + 1, res_mid)
bfs(node.right, level + 1, res_mid)
bfs(root, 0, res_mid)
return len(res_mid)
111.二叉树的最小深度
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
if not root.left and not root.right:
return 1
if not root.left:
min_depth = self.minDepth(root.right)+1
if not root.right:
min_depth = self.minDepth(root.left)+1
if root.left and root.right:
left = self.minDepth(root.left)+1
right = self.minDepth(root.right)+1
min_depth = min(left,right)
return min_depth
222.完全二叉树的节点个数
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
res = []
def bfs(node,level,res):
if not node:
return
if len(res) == level:
res.append([])
res[level].append(node.val)
bfs(node.left,level+1,res)
bfs(node.right,level+1,res)
bfs(root,0,res)
final = []
for i in res:
for j in i:
final.append(j)
return len(final)
110.平衡二叉树
class Solution:
def height(self, node): # 自下而上
if not node:
return 1
left_height = self.height(node.left)
right_height = self.height(node.right)
if left_height == -1:
return -1
if right_height == -1:
return -1
if abs(left_height - right_height) > 1:
return -1
else:
return 1 + max(left_height, right_height)
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if self.height(root)!=-1:
return True
else:
return False
257. 二叉树的所有路径
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
res = []
if not root:
return res
def dfs(root,path):
path += str(root.val)+'->'
if not root.left and not root.right:
res.append(path[:-2])
return
if root.left:
dfs(root.left,path)
if root.right:
dfs(root.right,path)
dfs(root,'')
return res