110.平衡二叉树 (优先掌握递归)
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解/视频讲解:代码随想录
解题思路:
设置一个新的递归function帮助解题 首先设置底层条件 然后开始递归左右子树个树 如果左或右子树上传回来的是-1 继续上传-1 这里-1的来源是如果上一层左右子树差大于1的话传回来的 反之不是-1的话 继续正常递归。
最后检验传回来的值。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def count(root):
if root is None:
return 0
left = count(root.left)
right = count(root.right)
if left == -1:
return -1
if right == -1:
return -1
if abs(left-right) > 1:
return -1
return 1 + max(left,right)
if count(root) == -1:
return False
return True
257. 二叉树的所有路径 (优先掌握递归)
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解/视频讲解:代码随想录
解题思路:
回溯思想 用前序遍历 因为我们要得到的结果是从root到leaf的。
设置一个变量记录单条路径 并设计一条变量记录总结。
设置一个递归function 首先设置底层条件。然后做中的递归 当左右子树皆为空的话 说明这一条路径走到了尾 就把当前路径放进结果里。接着做左子树的递归, 注意传路径是要加“->", 右子树也一样。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def binaryTreePaths(self, root):
"""
:type root: TreeNode
:rtype: List[str]
"""
path=''
res=[]
def traversal(root,path,res):
if not root:
return res
path += str(root.val)
if not root.left and not root.right:
res.append(path)
if root.left:
traversal(root.left,path+'->',res)
if root.right:
traversal(root.right,path+'->',res)
return res
return traversal(root,path,res)
404.左叶子之和 (优先掌握递归)
题目链接:LeetCode - The World's Leading Online Programming Learning Platform
题目链接/文章讲解/视频讲解:代码随想录
解题思路:
使用后序遍历 首先设置底层条件。 然后递归左右子树 当递归中的时候要判断是否有左叶子树(root.left and root.left.left == None and root.left.right == None)如果有的话 就要把这个值加入到最后结合的数中。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
left = self.sumOfLeftLeaves(root.left)
right = self.sumOfLeftLeaves(root.right)
sum = 0
if root.left and root.left.left == None and root.left.right == None:
sum = root.left.val
return sum + left +right