叉树的右视图这道算法题可以用递归解决的Java实现的代码
时间: 2023-03-30 10:01:06 浏览: 55
可以的,以下是Java实现的代码:
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
if (root == null) return res;
helper(root, res, );
return res;
}
private void helper(TreeNode node, List<Integer> res, int depth) {
if (node == null) return;
if (depth == res.size()) res.add(node.val);
helper(node.right, res, depth + 1);
helper(node.left, res, depth + 1);
}
相关问题
二叉树的右视图这道算法题可以用递归解决的Java实现的代码
可以的,以下是Java实现的代码:
```
class Solution {
public List<Integer> rightSideView(TreeNode root) {
List<Integer> res = new ArrayList<>();
dfs(root, res, );
return res;
}
private void dfs(TreeNode node, List<Integer> res, int depth) {
if (node == null) return;
if (depth == res.size()) res.add(node.val);
dfs(node.right, res, depth + 1);
dfs(node.left, res, depth + 1);
}
}
```
这段代码可以求出二叉树的右视图。
java 整数划分问题递归算法的实现 代码
好的,以下是 Java 整数划分问题递归算法的实现 代码:
```java
public class IntegerPartition {
public static int integerPartition(int n, int m) {
if (n == 1 || m == 1) {
return 1;
}
if (n < m) {
return integerPartition(n, n);
} else if (n == m) {
return integerPartition(n, m - 1) + 1;
} else {
return integerPartition(n, m - 1) + integerPartition(n - m, m);
}
}
public static void main(String[] args) {
int n = 5;
int m = 5;
System.out.println(integerPartition(n, m));
}
}
```
这个代码用递归的方式实现了整数划分问题的求解,其中n是待划分的整数,m是最大划分值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)