【代码随想录训练营】【Day 20】【二叉树-4】| Leetcode 110, 257, 404
需强化知识点
- 回溯:result.append (path[:])
题目
110. 平衡二叉树
- 注意 这道题是要求节点的高度,首先递归得到左右子树的高度,如果高度差 > 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: Optional[TreeNode]) -> bool:
if not root:
return True
flag = self.getHeight(root)
if flag == -1:
return False
return True
def getHeight(self, root):
if not root:
return 0
leftHeight = self.getHeight(root.left)
if leftHeight == -1:
return -1
rightHeight = self.getHeight(root.right)
if rightHeight == -1:
return -1
if abs(leftHeight - rightHeight) > 1:
return -1
return 1 + max(leftHeight, rightHeight)
257. 二叉树的所有路径
- 注意 result.append (path[:]),有被坑到
- 在 Python 中,map() 函数用于对可迭代对象中的每个元素应用指定的函数。当函数应用于可迭代对象的每个元素时,它将返回一个迭代器,其中包含应用函数后的结果。在给定的示例中,map(str, a_list) 将应用 str 函数到列表 a_list 中的每个元素。str 函数用于将给定的参数转换为字符串类型。
# 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 binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
if not root:
return []
result = []
def backtracking(root, result, path):
if not root.left and not root.right:
# sPath = '->'.join(map(str, path))
result.append(path[:])
return
if root.left:
path.append(root.left.val)
backtracking(root.left, result, path)
path.pop()
if root.right:
path.append(root.right.val)
backtracking(root.right, result, path)
path.pop()
backtracking(root, result, [root.val])
result = ['->'.join(map(str, path)) for path in result]
return result
404. 左叶子之和
- 注意左叶子的判定条件(要基于父亲节点进行判断),递归法有点不好理解,先掌握迭代法
# 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 sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
# if not root.left and not root.right:
# return 0
# leftValue = self.sumOfLeftLeaves(root.left)
# if root.left and not root.left.left and not root.left.right:
# leftValue = root.left.val
# rightValue = self.sumOfLeftLeaves(root.right)
# return leftValue + rightValue
sum_ = 0
que = collections.deque([root])
while que:
size = len(que)
for _ in range(size):
cur = que.popleft()
if cur.left:
if not cur.left.left and not cur.left.right:
sum_ += cur.left.val
que.append(cur.left)
if cur.right:
que.append(cur.right)
return sum_