文章目录
-
- 层序遍历
-
- [102 二叉树的层序遍历](#102 二叉树的层序遍历)
- [226 翻转二叉树](#226 翻转二叉树)
- [101 对称二叉树](#101 对称二叉树)
层序遍历
队列先进先出,符合一层一层遍历的逻辑,而用栈先进后出适合模拟深度优先遍历也就是递归的逻辑。
102 二叉树的层序遍历
python
class Solution:
def levelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
levels = []
self.helper(root, 0, levels)
return levels
def helper(self, node, level, levels):
if not node:
return
if len(levels) == level:
levels.append([])
levels[level].append(node.val)
self.helper(node.left, level + 1, levels)
self.helper(node.right, level + 1, levels)
python
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
226 翻转二叉树
初始思路 :
使用递归。先处理root,如果是None,则return None。接着将反转的root.left赋给root.right,另一边也一样。
python
class Solution(object):
def invertTree(self, root):
if not root:
return None
tmp = root.left
root.left = self.invertTree(root.right)
root.right = self.invertTree(tmp)
return root
注:这是递归法的前序遍历,其余遍历方法和迭代法需要之后补充
101 对称二叉树
初始思路 :
root.left和root.right两个子树在一方反转后是否相等。但空间复杂度不太妙,还需要多traverse一次,应该直接在traverse中查看是否对称。
python
class Solution(object):
def invertTree(self, root):
if not root:
return None
tmp = root.left
root.left = self.invertTree(root.right)
root.right = self.invertTree(tmp)
return root
def compare(self, left, right):
if not left and not right:
return True
if not left or not right:
return False
if left.val == right.val:
return self.compare(left.left, right.left) and self.compare(left.right, right.right)
return False
def isSymmetric(self, root):
# invert tree and see if it is the same as itself
if not root:
return True
invert_left = self.invertTree(root.left)
return self.compare(invert_left, root.right)
python
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
return self.compare(root.left, root.right)
def compare(self, left, right):
#首先排除空节点的情况
if left == None and right != None: return False
elif left != None and right == None: return False
elif left == None and right == None: return True
#排除了空节点,再排除数值不相同的情况
elif left.val != right.val: return False
#此时就是:左右节点都不为空,且数值相同的情况
#此时才做递归,做下一层的判断
outside = self.compare(left.left, right.right) #左子树:左、 右子树:右
inside = self.compare(left.right, right.left) #左子树:右、 右子树:左
isSame = outside and inside #左子树:中、 右子树:中 (逻辑处理)
return isSame
注:这是递归法的前序遍历,其余遍历方法和迭代法需要之后补充