LC110:平衡二叉树:
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if self.get_height(root) != -1:
return True
else:
return False
def get_height(self,root:TreeNode) -> int:
if not root:
return 0
if (left_height := self.get_height(root.left)) == -1: #左
return -1
if (right_height := self.get_height(root.right)) == -1: #右
return -1
if abs(left_height - right_height) > 1: #中
return -1
else:
return 1 + max(left_height, right_height)
递归无敌。-1 表示已经不是平衡二叉树了,否则返回值是以该节点为根节点树的高度。
LC257:二叉树的所有路径:
class Solution:
def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]:
path = ''
res = []
if not root:
return res
self.traversal(root, path, res)
return res
def traversal(self, cur: TreeNode, path: str, res: List[str]) -> None:
path += str(cur.val)
if not cur.left and not cur.right:
res.append(path)
if cur.left:
self.traversal(cur.left, path + '->', res)
if cur.right:
self.traversal(cur.right, path + '->', res)
要有path 和 res 来记录。
LC404:左叶子之和:
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
left_left_leaves_sum = self.sumOfLeftLeaves(root.left)
right_left_leaves_sum = self.sumOfLeftLeaves(root.right)
cur_left_leaf_val = 0
if root.left and not root.left.left and not root.left.right:
cur_left_leaf_val = root.left.val
return cur_left_leaf_val + left_left_leaves_sum + right_left_leaves_sum
注意是左叶子不是左侧节点