层序遍历 10
给你二叉树的根节点 root
,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
解题思路:
设置一个新的deque用来存储遍历的节点,弹出每个最左边的节点,检查是否有左右children, 有的话加入deque,每一层设置一个新的list用来存储这一层的节点value,list针对每一层都会更新。
代码如下:
# 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 levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
res = []
queue = collections.deque([root])
#while queue exists pop out the elements in order
while queue:
lst = []
for _ in range(len(queue)):
node = queue.popleft()
lst.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(lst)
return res
226.翻转二叉树
给你一棵二叉树的根节点 root
,翻转这棵二叉树,并返回其根节点。
解题思路:
递归三步骤
- 确定输入:def swap(root)
- 确定停止条件:if not root: return None 到达最底端停止
- 递归逻辑:root.left, root.right = root.right, root.left
-
# 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 invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]: if not root: return res = [] def swap(root): if not root: return None root.left, root.right = root.right, root.left swap(root.left) swap(root.right) swap(root) return root
101.对称二叉树
给你一个二叉树的根节点 root
, 检查它是否轴对称。
解题思路:
递归三步骤
确定输入和参数:def compare(left, right)比较左右两边,因此输入left child nad right child
确定停止条件:not left, right; left, not right; not left, not right(return True); left.val != righ.val
递归逻辑:left.val == right.val继续对比left.left, right.right;left.right, right.left
# 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 isSymmetric(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
def compare(left, right):
if not left and not right:
return True
elif not left and right:
return False
elif left and not right:
return False
elif left.val != right.val:
return False
#continue comparing
left_side = compare(left.left, right.right)
right_side = compare(left.right,right.left)
return left_side and right_side
return compare(root.left, root.right)