110.平衡二叉树
# 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 getDepth(self, root):
if root is None:
return 0
left = self.getDepth(root.left)
right = self.getDepth(root.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
else:
return 1+max(left, right)
def isBalanced(self, root: Optional[TreeNode]) -> bool:
return self.getDepth(root) != -1
257. 二叉树的所有路径
# 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]:
result = []
temp = ""
self.findPath(root, temp, result)
return result
def findPath(self, root, temp, result):
if root is None:
return
elif root.left is None and root.right is None:
if temp:
temp += "->"
temp += str(root.val)
result.append(temp)
temp = ""
else:
if temp:
temp += "->"
temp += str(root.val)
self.findPath(root.left, temp, result)
self.findPath(root.right, temp, result)
404.左叶子之和
标签:right,temp,17,self,随想录,二叉树,root,left From: https://www.cnblogs.com/miramira/p/18117604