110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced
class Solution:
def __init__(self):
self.flag=True
def isBalanced(self, root: Optional[TreeNode]) -> bool:
def dfs(root):
if not root:
return 0
h_l = dfs(root.left)
h_r = dfs(root.right)
if h_l>h_r+1 or h_r > h_l+1:
self.flag = False
return max(h_l,h_r)+1
h = dfs(root)
return self.flag
404. Sum of Left Leaves
Given the
root
of a binary tree, return the sum of all left leaves.A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.
Example 1:
![]()
Input: root = [3,9,20,null,null,15,7] Output: 24 Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
sum_v = 0
def dfs(root):
nonlocal sum_v
if not root:
return 0
left_kid = root.left
if left_kid:
if not left_kid.left and not left_kid.right:
sum_v += left_kid.val
dfs(root.left)
dfs(root.right)
return sum_v
return dfs(root)
class Solution:
def __init__(self):
self.sum_v = 0
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
def dfs(root):
if not root:
return 0
left_kid = root.left
if left_kid:
if not left_kid.left and not left_kid.right:
self.sum_v += left_kid.val
dfs(root.left)
dfs(root.right)
return self.sum_v
return dfs(root)
257. Binary Tree Paths
Given the
root
of a binary tree, return all root-to-leaf paths in any order.A leaf is a node with no children.
Example 1:
Input: root = [1,2,3,null,5] Output: ["1->2->5","1->3"]
class Solution: #回溯
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
res = []
path = []
def backtracking(node):
if not node:
return
path.append(str(node.val)) #mid
if not node.left and not node.right: #1 end condition
res.append("->".join(path))
return
if node.left: #2 loop (flattend for binary tree for left and right)
backtracking(node.left) #3. recur
path.pop() #4. pop
if node.right:
backtracking(node.right)
path.pop()
return
backtracking(root)
return res