代码随想录算法训练营第十七天|110.平衡二叉树,257. 二叉树的所有路径,404.左叶子之和
110.平衡二叉树
题目链接:平衡二叉树
这次刷题算是自己第一次不看答案写迭代吧,想记录一些错误。
一些错误
没递归起来
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
if (not root.right) and (not root.right):
return True
def height(root):
if not root:
return 0
return max(height(root.left),height(root.right))+1
return (abs(height(root.left)-height(root.right))<=1)
这里就直接比了root的左子树和右子树,别的子树就都不管了,然后就出现了这种例子。
递归起来了,但被打断了
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def height(root):
if not root:
return 0
return max(height(root.left),height(root.right))+1
if not root:
return True
if (abs(height(root.left)-height(root.right))<=1):
return True
else:
return False
return self.isBalanced(root.left) and self.isBalanced(root.right)
我本来想的是function会一直走到最后一个return,这样就可以形成一个只有全T才会T的and形式,但function是在没有触发前面所有的return之后才会走到最后一个return,只要触发了就会被打断,后面写出花都啥也没有。
所以开始考虑自己的这个逻辑问题,我是想有>1的情况下直接出False,如果这次的左右子树是True就再往下比较。想清楚了就知道在中间的return上就应该有操作。
递归
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def height(root):
if not root:
return 0
return max(height(root.left),height(root.right))+1
if not root:
return True
if (abs(height(root.left)-height(root.right))<=1):
return True and (self.isBalanced(root.left) and self.isBalanced(root.right))
else:
return False
257. 二叉树的所有路径
题目链接:二叉树的所有路径
回溯
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
def travesal(root,path,result):
path += str(root.val)
if (not root.left) and (not root.right):
result.append(path)
else:
path += '->'
if root.left:
travesal(root.left,path,result)
if root.right:
travesal(root.right,path,result)
result = []
path = ''
if not root:
return result
travesal(root,path,result)
return result
在往左往右哪里有隐形的回溯,虽然我感觉更加像是分叉了,左边一条路,右边一条路。还没学回溯专题就先这么理解吧。
这里的隐形回溯成立是因为path是一个值,进去递归之后可以生成新的值出来,但是如果path是list的话所有操作都是append,不会有新的list,后面要pop掉才叫回溯。
404.左叶子之和
题目链接:左叶子之和
这个题是左叶子,是叶子节点,不是随便一个左节点就可以的
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
if root.left and (not root.left.left and not root.left.right):
return root.left.val+self.sumOfLeftLeaves(root.right)
else:
return self.sumOfLeftLeaves(root.left)+self.sumOfLeftLeaves(root.right)