翻转二叉树
给你一棵二叉树的根节点 root ,翻转这棵二叉树,并返回其根节点。
示例 1:
输入:root = [4,2,7,1,3,6,9]
输出:[4,7,2,9,6,3,1]
递归法
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
# print("*********")
# print("root:", root)
return None
print(root.val)
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
层序遍历法
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
queue = collections.deque([root])
while queue:
for _ in range(len(queue)):
node = queue.popleft()
print(node.val)
print('*********')
node.right, node.left = node.left, node.right
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return root
对称二叉树
给你一个二叉树的根节点 root , 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3]
输出:true
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
return self.compare(root.left, root.right)
def compare(self, left, right):
# 先检查如果两边都为空,那么它们是对称的
if left is None and right is None:
return True
# 如果一边为空而另一边不为空,则它们不对称
if left is None or right is None:
return False
# 如果两边的值不相等,也不对称
if left.val != right.val:
return False
# 递归比较外侧和内侧
outside = self.compare(left.left, right.right)
inside = self.compare(left.right, right.left)
return outside and inside
完全二叉树的节点个数
给你一棵 完全二叉树 的根节点 root ,求出该树的节点个数。
完全二叉树 的定义如下:在完全二叉树中,除了最底层节点可能没填满外,其余每层节点数都达到最大值,并且最下面一层的节点都集中在该层最左边的若干位置。若最底层为第 h 层,则该层包含 1~ 2h 个节点。
输入:root = [1,2,3,4,5,6]
输出:6
# 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 root is None:
return 0
leftNumber = self.countNodes(root.left)
rightNumber = self.countNodes(root.right)
total = leftNumber + rightNumber + 1
return total
平衡二叉树
给定一个二叉树,判断它是否是高度平衡的二叉树。
本题中,一棵高度平衡二叉树定义为:
一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
if abs(left -right) <= 1: # 表示属于平衡节点 因此 return max(left, right) + 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 isBalanced(self, root: TreeNode) -> bool:
def recur(root):
if not root:
return 0
left = recur(root.left)
if left == -1:
return -1
right = recur(root.right)
if right == -1:
return -1
if abs(left -right) <= 1:
return max(left, right) + 1
else:
return -1
return recur(root) != -1