第7课-泛型递归、树的递归


树的面试题解法一般都是递归

  1. 节点的定义
  2. 重复性(自相似性)

示例代码

def preorder(self, root):
  if root:
    self.traverse_path.append(root.val)
    self.preorder(root.left)
    self.preorder(root.right)
def inorder(self, root):
  if root:
    self.inorder(root.left)
    self.traverse_path.append(root.val)
    self.inorder(root.right)
def postorder(self, root):
  if root:
    self.postorder(root.left)
    self.postorder(root.right)
    self.traverse_path.append(root.val)

递归 Recursion

递归 - 循环
通过函数体来进行的循环

  1. 从前有个山
  2. 山里有个庙
  3. 庙里有个和尚讲故事
  4. 返回1

盗梦空间

  • 向下进入到不同梦境中;向上又回到原来一层
  • 通过声音同步回到上一层
  • 每一层的环境和周围的人都是一份拷贝、
    主角等几个人穿越不同层级的梦境(发生和携带变化)

计算 n!

计算 n!
n!= 1 * 2 * 3 * ... * n
def Factorial(n): 
	if n <= 1:
        return 1
    return n * Factorial(n — 1)

在这里插入图片描述

Python 代码模版

def recursion(level, param1, param2, ...):
     # recursion terminator
     # 递归终结条件
     if level > MAX_LEVEL:
       process_result
	   return
     # process logic in current level
     # 处理当前层逻辑
     process(level, data...)
     # drill down
     # 下探到下一层
     self.recursion(level + 1, p1, ...)
     # reverse the current level status if needed
     # 清理当前层

Java 代码模版

public void recur(int level, int param) {
     // terminator
     if (level > MAX_LEVEL) {
       // process result
	 	return; 
	 }
     // process current logic
     process(level, param);
     // drill down
     recur( level: level + 1, newParam);
     // restore current status
}

思维要点

  1. 不要人肉进行递归(最大误区)
  2. 找到最近最简方法,将其拆解成可重复解决的问题(重复子问题)
  3. 数学归纳法思维

实战题目

  1. https://leetcode-cn.com/problems/climbing-stairs/
  2. https://leetcode-cn.com/problems/generate-parentheses/

实战题目

  1. https://leetcode-cn.com/problems/invert-binary-tree/description/
  2. https://leetcode-cn.com/problems/validate-binary-search-tree
  3. https://leetcode-cn.com/problems/maximum-depth-of-binary- tree
  4. https://leetcode-cn.com/problems/minimum-depth-of-binary-tree
  5. https://leetcode-cn.com/problems/serialize-and-deserialize- binary-tree/

Homework

  1. https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/
  2. https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
  3. https://leetcode-cn.com/problems/combinations/
  4. https://leetcode-cn.com/problems/permutations/
    https://leetcode-cn.com/problems/permutations-ii/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值