js 修改tree指定的节点的多个值
时间: 2024-02-11 10:06:58 浏览: 27
要修改树中指定节点的多个值,同样需要先遍历整个树,找到需要修改的节点,然后更新该节点的多个值。
假设树的节点结构如下:
```javascript
class TreeNode {
constructor(val, attr1, attr2, attr3) {
this.val = val;
this.attr1 = attr1;
this.attr2 = attr2;
this.attr3 = attr3;
this.left = null;
this.right = null;
}
}
```
现在我们要修改树中的某个节点的多个值,可以先找到该节点,然后更新其属性值即可。以下是一个示例代码:
```javascript
function updateNodeAttrs(root, targetVal, newAttrs) {
if (!root) {
return;
}
if (root.val === targetVal) {
root.attr1 = newAttrs.attr1 || root.attr1;
root.attr2 = newAttrs.attr2 || root.attr2;
root.attr3 = newAttrs.attr3 || root.attr3;
}
updateNodeAttrs(root.left, targetVal, newAttrs);
updateNodeAttrs(root.right, targetVal, newAttrs);
}
```
这个函数接受三个参数:树的根节点 `root`、需要修改的节点的值 `targetVal`,以及新的节点属性值 `newAttrs`。函数会遍历整个树,找到值为 `targetVal` 的节点,然后将其指定的属性值更新为 `newAttrs` 中的属性值(如果存在)。如果 `newAttrs` 中没有指定某个属性值,则该属性值保持不变。注意,这个函数同样会修改原来的树,因此需要谨慎使用。
相关推荐
![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_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)