递归,是考虑大问题的时候包含了重复的小问题(比如计算树的深度,也就是计算根节点所在树的高度,左节点、右节点所在树的高度以此类推,这是递,归呢是到达边界条件,终止后往上回归结果。)在计算的时候也需要从上往下,从大往小,上面的先进,后出,这样的数据结构,就是熟悉的栈.
- 对于递归的终止条件,要考虑到叶节点下一层,也就是None那一层,是终止条件。
- 如果是bool类型的返回值,可以作为组合条件,return最终答案(见对称二叉树)
100. 相同的树
# 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 isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
# 终止条件
if p == None or q == None:
return p == q
#返回一般的
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
# 返回布尔值,所以这三个条件一起决定返回值
# 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 isSymmetric(self, root: Optional[TreeNode]) -> bool:
# 左等于右
return self.isSame(root.left, root.right)
def isSame(self, l: TreeNode, r: TreeNode) -> bool:
if l is None or r is None:
return l is r
return l.val == r.val and self.isSame(l.left, r.right) and self.isSame(l.right, r.left)
# 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 isBalanced(self, root: Optional[TreeNode]) -> bool:
# 左右深度差小于等于1
def depth(node: TreeNode):
# 如果有子树深度差大于1 返回-1,否则返回当前子树的深度
if node is None:
return 0
leftdepth = depth(node.left)
if leftdepth == -1:
return -1
rightdepth = depth(node.right)
if rightdepth == -1 or abs(rightdepth - leftdepth) > 1:
return -1
else:
return max(leftdepth, rightdepth) + 1
return depth(root) >= 0
199. 二叉树的右视图
层序遍历,注意queue([root])传入的得是[root]可迭代的变量
# 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 rightSideView(self, root: Optional[TreeNode]) -> List[int]:
# 左右子树最右边的一个,很像层序遍历,每层最右边的一个
if root is None:
return []
que = deque([root])# 'TreeNode' object is not iterable所以得[root]
ans = []
while que:
node = None
n = len(que)
for _ in range(n): # 先得到值
if node is None:
# 得始终保证是从左往右或者从右往左,所以是队列,先进先出
# 先进右
node = que.popleft()
ans.append(node.val)
else:
node = que.popleft()
if node.right:
que.append(node.right)
if node.left:
que.append(node.left)
return ans
法2:递归
先右子树,再左子树。什么时候记录数值?当递归深度大于答案长度时就记录。
递归函数是对某些变量进行修改,所以不需要有返回值,并且需要递归的初始条件
# 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 rightSideView(self, root: Optional[TreeNode]) -> List[int]:
ans = []
def f(node, depth):
if node is None:
return
if depth > len(ans):
ans.append(node.val)
f(node.right, depth+1)
f(node.left, depth+1)
f(root, 1)
return ans