第一题
Given a binary tree, determine if it is height-balanced
height-balanced的定义为:一棵二叉树中,左右两个子树的高度差不超过1。
既然要比较高度,必然需要后序遍历
class Solution:
def isBalanced(self, root: Optional[TreeNode]) -> bool:
if not root:
return True
height_map = {}
stack = [root]
while stack:
node = stack.pop()
if node:
stack.append(node)
stack.append(None)
if node.left: stack.append(node.left)
if node.right: stack.append(node.right)
else:
real_node = stack.pop()
left, right = height_map.get(real_node.left, 0), height_map.get(real_node.right, 0)
if abs(left - right) > 1:
return False
height_map[real_node] = 1 + max(left, right)
return True
第二题
Given the
root
of a binary tree, return all root-to-leaf paths in any order.A leaf is a node with no children.
这道题涉及到回溯,因为我们要把路径记录下来,需要回溯来回退一个路径再进入另一个路径。
还要结合递归,递归和回溯本是一家人
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):
result = []
path = []
if not root:
return result
self.traversal(root, path, result)
return result
第三题
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.
用递归的方法,后序遍历
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
if root.left is None and root.right is None:
return 0
leftValue = self.sumOfLeftLeaves(root.left)
if root.left and not root.left.left and not root.left.right:
leftValue = root.left.val
rightValue = self.sumOfLeftLeaves(root.right)
sum_val = leftValue + rightValue
return sum_val