今天来聊一聊一个经典的算法思想——递归。
递归:一种通过重复将问题分解为同类的子问题而解决问题的方法。
递归是当前算法题目和运算中一种很普遍、很常用的算法思想,在很多问题尤其是二叉树的相关问题上是简化分析和编程的尤其常用的巧。
计算理论可以证明递归的作用可以完全取代循环,因此在很多函数编程语言中习惯用递归来实现循环。
int func(int n){//定义阶乘函数
if(n==1 || n==0) return 1;//输入的参数是0或者1,直接返回1
return n*func(n-1);//递归算法调用
}
int getDepth(TreeNode root)
if(root == null) return 0;
int leftDepth = getDepth(root.left);
int rightDepth = getDepth(root.right);
int depth = Math.max(leftDepth, rightDepth) + 1;
return depth;
public int maxDepth(TreeNode root) {
return getDepth(root);
}
public int getDepth(TreeNode root) {
if(root == null) return 0;
int leftDepth = getDepth(root.left);
int rightDepth = getDepth(root.right);
int depth = Math.max(leftDepth, rightDepth) + 1;
return depth;
}
int maxDepth(TreeNode root) {
if (root == null) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
package com.camunda.annotation;
import java.util.LinkedList;
import java.util.Queue;
public class SolutionTree {
public int maxDepth(TreeNode root) {
if (root == null) {
return 0;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int ans = 0;
while (!queue.isEmpty()) {
int size = queue.size();
while (size > 0) {
TreeNode node = queue.poll();
if (root.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
size--;
}
ans++;
}
return ans;
}
static class TreeNode {
private int value;// 头节点
private TreeNode left;// 左树
private TreeNode right;// 右树
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public TreeNode getLeft() {
return left;
}
public void setLeft(TreeNode left) {
this.left = left;
}
public TreeNode getRight() {
return right;
}
public void setRight(TreeNode right) {
this.right = right;
}
}
}
以上内容介绍了递归定义,讲解了“递归三部曲”并详细介绍了它的简单应用,举例说明了其中应当注意的地方。
读者应当加强练习,有针对性的进行训练。