劍指Offer之Java算法習(xí)題精講二叉樹與斐波那契函數(shù)
更新時間:2022年03月18日 10:35:59 作者:明天一定.
跟著思路走,之后從簡單題入手,反復(fù)去看,做過之后可能會忘記,之后再做一次,記不住就反復(fù)做,反復(fù)尋求思路和規(guī)律,慢慢積累就會發(fā)現(xiàn)質(zhì)的變化
題目一

解法
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;
}
}
到此這篇關(guān)于劍指Offer之Java算法習(xí)題精講二叉樹與斐波那契函數(shù)的文章就介紹到這了,更多相關(guān)Java二叉樹與斐波那契函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java線程編程中isAlive()和join()的使用詳解
這篇文章主要介紹了Java線程編程中isAlive()和join()的使用詳解,是Java入門學(xué)習(xí)中的基礎(chǔ)知識,需要的朋友可以參考下2015-09-09
Springcloud seata nacos環(huán)境搭建過程圖解
這篇文章主要介紹了Springcloud seata nacos環(huán)境搭建過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-03-03
多數(shù)據(jù)源如何實現(xiàn)事務(wù)管理
Spring中涉及三個核心事務(wù)處理接口:PlatformTransactionManager、TransactionDefinition和TransactionStatus,PlatformTransactionManager提供事務(wù)操作的基本方法,如獲取事務(wù)、提交和回滾2024-09-09
SpringBoot如何使用@RequestBody進(jìn)行數(shù)據(jù)校驗
在Web開發(fā)中,前臺向后臺發(fā)送數(shù)據(jù)是非常常見的場景,而在SpringBoot框架中,我們通常使用@RequestBody注解來接收前臺發(fā)送的?JSON數(shù)據(jù),并將其轉(zhuǎn)化為Java對象,本文將介紹如何在?SpringBoot?中使用?@RequestBody?進(jìn)行數(shù)據(jù)校驗2023-06-06

