110、平衡二叉树:
class Solution(object):
def get_height(self, root):
if not root:
return 0
return max(self.get_height(root.left), self.get_height(root.right))+1
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
left = self.isBalanced(root.left)
right = self.isBalanced(root.right)
sub = abs(self.get_height(root.left) - self.get_height(root.right)) <= 1
return left and right and sub
通过后序遍历来递归的判断是否为平衡二叉树
257、二叉树的所有路径:
class Solution(object):
def traversal(self, root, path, res):
path.append(root.val)
if not root.left and not root.right:
res.append('->'.join([str(item) for item in path]))
return res
if root.left:
self.traversal(root.left, path, res)
path.pop()
if root.right:
self.traversal(root.right, path, res)
path.pop()
return res
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
return self.traversal(root, [], [])
这道题是前序遍历的方式,应为所有路径必然要从root开始向下遍历获得,值得注意的是在遍历左右子树时,需要回溯,回溯和递归是一起的,每一次递归都伴随着一次回溯
404、左叶子之和:
class Solution(object):
def __init__(self):
self.init_value = 0
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return
if root.left and not root.left.left and not root.left.right:
self.init_value += root.left.val
self.sumOfLeftLeaves(root.left)
self.sumOfLeftLeaves(root.right)
return self.init_value
这道题的关键是左叶子的定义,要通过父节点来判断,左叶子必须是叶子节点