第一题
102. Binary Tree Level Order Traversal
Given the
root
of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).
昨天在整理基础知识的时候,提到了层序遍历是广度优先遍历的一种。
这道题的解法用到了队列,同时还要有一个变量来记录每一层有几个数,这样来保证出队列的时候,分清楚每一层有几个。
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
queue = collections.deque([root])
result = []
while queue:
level = []
for _ in range(len(queue)):
cur = queue.popleft()
level.append(cur.val)
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
result.append(level)
return result
第二题
Given the
root
of a binary tree, invert the tree, and return its root.
这道题前序遍历和后序遍历都可以,唯独中序遍历不方便,因为有可能会把一些节点反转两次
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return None
stack = [root]
while stack:
node = stack.pop()
node.left, node.right = node.right, node.left
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return root
第三题
Given the
root
of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
这道题,其实我们要比较的是两个树(这两个树是根节点的左右子树)
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
st = []
st.append(root.left)
st.append(root.right)
while st:
rightNode = st.pop()
leftNode = st.pop()
if not leftNode and not rightNode:
continue
if not leftNode or not rightNode or leftNode.val != rightNode.val:
return False
st.append(leftNode.left)
st.append(rightNode.right)
st.append(leftNode.right)
st.append(rightNode.left)
return True