怎么判断树里的值与一特定值相同并将相同的值传入arraylist
时间: 2024-03-23 13:36:07 浏览: 12
可以通过遍历树来判断树中的值是否与特定值相同,并将相同的值加入到ArrayList中。具体实现可以使用深度优先搜索算法,遍历树的每个节点,如果节点的值与特定值相同,则将该节点的值添加到ArrayList中。实现代码如下:
```
public void findValues(TreeNode root, int target, List<Integer> list) {
if (root == null) {
return;
}
if (root.val == target) {
list.add(root.val);
}
findValues(root.left, target, list);
findValues(root.right, target, list);
}
```
其中,`root`为树的根节点,`target`为特定值,`list`为存储相同值的ArrayList。函数会遍历整个树,将所有与特定值相同的节点的值添加到ArrayList中。
相关问题
怎么判断树里的值与一特定值相同并将相同的值传入arraylist最终返回arraylist
可以在findValues函数中添加一个返回值,用于存储到的所有与特定相同的节点的。具体实现可以使用深度优先搜索算法,遍历树的每个节点,如果节点的值与特定值同,则将该节点的值添加到ArrayList中最终将存储相同值的ArrayList返回实现代码如下:
```
public List<Integer> findValues(TreeNode root, int target) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
if (root.val == target) {
list.add(root.val);
}
list.addAll(findValues(root.left, target));
list.addAll(findValues(root.right, target));
return list;
}
```
其中,`root`为树的根节点,`target`为特定值。函数会遍历整个树,将所有与特定值相同的节点的值添加到ArrayList中,最终将存储相同值的ArrayList返回。调用该函数可以如下所示:
```
List<Integer> list = findValues(root, target);
```
其中,`root`为树的根节点,`target`为特定值,`list`为存储相同值的ArrayList。函数会返回所有与特定值相同的节点的值。
java判断list是否有相同的值
可以使用Set来判断List中是否有相同的值。首先将List添加到Set中,如果Set的大小小于List的大小,则说明List中有相同的值。代码示例:
List<Integer> list = new ArrayList<>();
Set<Integer> set = new HashSet<>();
list.add(1);
list.add(2);
list.add(3);
list.add(1);
set.addAll(list);
if(set.size() < list.size()) {
System.out.println("List中有相同的值");
} else {
System.out.println("List中没有相同的值");
}
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)