Java中二叉树与斐波那契函数的实例分析
作者:慢热型
时间:2023-04-27
来源:互联网
浏览:0
题目一解法classSolution{publicintfib(intn){int[]arr=newint[31];arr[0]=0;arr[1]=1;for(inti=2;i
题目一

解法
class Solution {
public int fib(int n) {
int[] arr = new int[31];
arr[0] = 0;
arr[1] = 1;
for(int i = 2;i<=n;i++){
arr[i] = arr[i-2]+arr[i-1];
}
return arr[n];
}
}题目二

解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int index = 0;
int ans = 0;
public int kthSmallest(TreeNode root, int k) {
method(root,k);
return ans;
}
void method(TreeNode root, int k){
if(root==null) return;
method(root.left,k);
index++;
if(index==k){
ans = root.val;
return;
}
method(root.right,k);
}
}题目三

解法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return 1;
}
int min_depth = Integer.MAX_VALUE;
if (root.left != null) {
min_depth = Math.min(minDepth(root.left), min_depth);
}
if (root.right != null) {
min_depth = Math.min(minDepth(root.right), min_depth);
}
return min_depth + 1;
}
}
作者最新文章
网易2026年Q2财报:营收301亿元,游戏收入增10%,三款重点新游披露进展
2026-09-08 17:51
PDF怎么添加页码?页码位置和起始页怎么设置?
2026-09-03 09:11
图片文件怎么转换成PDF?多张图片如何按顺序合成?
2026-09-02 19:33
CorelDRAW绘制正弦曲线的两种方法:贝塞尔工具与变形工具
2026-09-02 16:08
Excel工作表制作教程:设计易填写、易统计的业务表
2026-09-02 12:11
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















