110. 平衡二叉树
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
leftH=self.getDepth(root.left)
right=self.getDepth(root.right)
cha=abs(leftH-right)
if cha<=1 and self.isBalanced(root.right) and self.isBalanced(root.left):
return True
else:
return False
def getDepth(self,node):
if not node:
return 0
leftHeight=self.getDepth(node.left)
rightHeight=self.getDepth(node.right)
Depth=1+max(leftHeight,rightHeight)
return Depth
这题的思路就是判断根节点的左右字数是否平衡,就转化为根节点左右子树的高度差。但是需要注意也要判断是否每个子节点都有子节点。体现在代码上的就是,就是把子树看做根节点看是否有高度差。
self.isBalanced(root.right) and self.isBalanced(root.left)
257. 二叉树的所有路径
二叉树的所有路径
这题很明显使用递归来写,
(1) 找出重复的子问题。
前序遍历的顺序是:根节点、左子树、右子树。
在本题同样也是这个顺序:将根节点加入路径,递归左子树,递归右子树。
对于左子树和右子树来说,也都是同样的操作
class Solution:
def getPaths(self, root, path, res):
if not root:
return
# 节点值加入当前路径
path += str(root.val)# 字符串格式
# 如果当前节点是叶子节点,将当前路径加入结果集
if root.left == None and root.right == None:
res.append(path)
# 如果当前节点不是叶子节点,继续遍历左子树和右子树。
else:
path += '->'
self.getPaths(root.left, path, res)
self.getPaths(root.right, path, res)
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
res = []
path=''
self.getPaths(root, path, res)
return res
404. 左叶子之和
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
res=[]
self.findleft(root,res)
return sum(res)
def findleft(self,root,res):
if not root:
return
if root.left and not root.left.left and not root.left.right:
res.append(root.left.val)
self.findleft(root.left,res)
self.findleft(root.right,res)
我使用了递归函数,res是每个递归调用共享的变量,不是每次都创建一次。可以参考视频:carl