js实现当前存在一组数组,数组中为id的集合,取出这组数组每一个id在一个任意层级的树形结构体中的所有上级id,输出一个不会重复的数组
时间: 2024-05-02 18:19:39 浏览: 16
这个问题可以回答,可以使用递归来遍历树形结构体,判断每一个节点是否存在于给定的数组中,如果存在,则将其所有的上级id加入到一个集合中,最后输出集合中的元素即可,也可以使用非递归方式来实现。具体实现可以参考如下代码:
```
function findParentIds(tree, ids) {
const parentIds = new Set();
const stack = [...tree];
while (stack.length > 0) {
const node = stack.pop();
if (ids.includes(node.id)) {
let parent = node.parent;
while (parent !== null) {
parentIds.add(parent.id);
parent = parent.parent;
}
}
if (node.children) {
stack.push(...node.children);
}
}
return [...parentIds];
}
```
其中,`tree`是树形结构体,`ids`是要查找的id集合。函数返回的是不会重复的上级id集合。
相关问题
在成员变量声明一个Qpushbuton的数组后怎么给每个数组元素实例化一个对象
在成员变量声明一个QPushButton类型的数组后,你需要在类的构造函数中为每个数组元素实例化一个QPushButton对象。可以使用循环来遍历数组,并使用QPushButton的构造函数来实例化每个QPushButton对象。例如:
```cpp
class MyClass {
private:
QPushButton myButtons[3];
public:
MyClass() {
for (int i = 0; i < 3; i++) {
myButtons[i] = QPushButton(QString("Button %1").arg(i + 1), this);
myButtons[i].setFixedSize(100, 50);
// 设置其他属性
}
}
};
```
在上面的例子中,我们在MyClass的构造函数中遍历了数组,并使用QPushButton的构造函数来为每个数组元素实例化一个QPushButton对象。构造函数的第一个参数是按钮的文本,第二个参数是指定按钮的父对象,这里我们使用this作为父对象,表示按钮是MyClass的一个子组件。然后我们设置了按钮的固定大小和其他属性。注意,这里使用了赋值运算符来将QPushButton对象赋值给数组元素,这是因为QPushButton类有一个默认的复制构造函数和复制赋值运算符。
编写一个Java程序,去除一个数组中为0的元素组成一个新的数组
好的,下面是一个示例的Java程序:
```java
public class RemoveZeroFromArray {
public static void main(String[] args) {
int[] arr = {1, 0, 2, 0, 3};
int[] newArr = removeZero(arr);
for (int i : newArr) {
System.out.print(i + " ");
}
}
public static int[] removeZero(int[] arr) {
int count = 0;
for (int i : arr) {
if (i != 0) {
count++;
}
}
int[] newArr = new int[count];
int index = 0;
for (int i : arr) {
if (i != 0) {
newArr[index++] = i;
}
}
return newArr;
}
}
```
这个程序会输出:`1 2 3`。
程序中的 `removeZero` 方法会遍历一遍原数组,统计出不为0的元素的个数,然后创建一个新的数组,将不为0的元素放入新数组中返回。这样就去除了原数组中为0的元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)