商城首页欢迎来到中国正版软件门户

您的位置:首页 >Java中二叉树与斐波那契函数的实例分析

Java中二叉树与斐波那契函数的实例分析

  发布于2023-05-01 阅读(0)

扫一扫,手机访问

题目一

Java中二叉树与斐波那契函数的实例分析

解法

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];
    }
}

题目二

Java中二叉树与斐波那契函数的实例分析

 解法

/**
 * 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);
    }
}

题目三

Java中二叉树与斐波那契函数的实例分析

解法

/**
 * 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;
    }
}
本文转载于:https://www.yisu.com/zixun/691098.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注