title: LEETCODE-DAY17
date: 2024-03-09 14:15:21
tags:
今日内容:110.平衡二叉树 、257. 二叉树的所有路径 、404.左叶子之和
T1
class Solution:
#求一个节点的高度
def get_height(self,node):
if not node:
return 0
else:
return max(self.get_height(node.left),self.get_height(node.right))+1
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
q=deque()
q.append(root)
while q:
temp=q.popleft()
if abs(self.get_height(temp.left)-self.get_height(temp.right))>1:
return False
if temp.right:
q.append(temp.right)
if temp.left:
q.append(temp.left)
return True
T2
class Solution:
def traversal(self, cur, path, result):
path.append(cur.val) # 中
if not cur.left and not cur.right: # 到达叶子节点
sPath = '->'.join(map(str, path))
result.append(sPath)
return
if cur.left: # 左
self.traversal(cur.left, path, result)
path.pop() # 回溯
if cur.right: # 右
self.traversal(cur.right, path, result)
path.pop() # 回溯
def binaryTreePaths(self, root):
result = []
path = []
if not root:
return result
self.traversal(root, path, result)
return result
T3
本题关键是左叶子定义:节点A的左孩子不为空,且左孩子的左右孩子都为空(说明是叶子节点),那么A节点的左孩子为左叶子节点
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
sum=0
q=deque()
if root:
q.append(root)
while q:
temp=q.pop()
if temp.left and not temp.left.left and not temp.left.right:
sum+=temp.left.val
if temp.left:
q.append(temp.left)
if temp.right:
q.append(temp.right)
return sum
要注意的是无法只利用temp来判断其是否为左叶子,必须借助其父节点