if(left_height := self.get_height(root.left)) == -1:
return -1
#------等价于-------- := 海象符
#left_height = self.get_height(root.left)
#if left_height == -1:
# return -1
#先算左子树高度,存到 left_height,如果是 -1(不平衡),直接返回 -1。
# 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 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: Optional[TreeNode]) -> List[str]:
result = []
path = []
if not root:
return result
self.traversal(root, path, result)
return result
#sPath = '->'.join(map(str, path))
#----------等价于----------------
#sPath = ""
#for i, num in enumerate(path):
# sPath += str(num)
# if i != len(path) - 1:
# sPath += "->"
#result.append(sPath)
#'->'.join(map(str, path))的作用是:
#把 path 里的每个数字转成字符串,然后用 ->连起来,形成题目要求的格式。
#Pythonic = 用 Python 的方式优雅地解决问题