js 对比两个tree,找出不同的节点并返回
时间: 2024-01-08 11:04:04 浏览: 148
可以使用递归的方式对两个树进行对比,逐层比较节点的值是否相同,如果不同则将该节点标记为不同,然后递归比较左子树和右子树。
代码示例:
```javascript
function diffTree(tree1, tree2) {
if (!tree1 && !tree2) {
return null;
}
if (!tree1 || !tree2) {
return {
val1: tree1 ? tree1.val : null,
val2: tree2 ? tree2.val : null,
diff: true
};
}
if (tree1.val !== tree2.val) {
return { val1: tree1.val, val2: tree2.val, diff: true };
}
const diffLeft = diffTree(tree1.left, tree2.left);
const diffRight = diffTree(tree1.right, tree2.right);
if (diffLeft || diffRight) {
return {
val1: tree1.val,
val2: tree2.val,
left: diffLeft,
right: diffRight
};
}
return null;
}
// 示例
const tree1 = {
val: 1,
left: { val: 2, left: null, right: null },
right: { val: 3, left: null, right: null }
};
const tree2 = {
val: 1,
left: { val: 2, left: null, right: null },
right: { val: 4, left: null, right: null }
};
console.log(diffTree(tree1, tree2)); // { val1: 3, val2: 4, diff: true }
```
上述代码中,`diffTree` 函数接收两个树作为参数,如果两个树都为空,则返回 `null`,如果其中一个树为空,则返回该节点的值和 `diff` 标记为 `true`,表示两个树的结构不同。如果两个节点的值不同,则返回该节点的值和 `diff` 标记为 `true`。如果两个节点的值相同,则递归比较左子树和右子树,如果左子树或右子树中有不同的节点,则返回该节点的值和子树的 diff 结果。如果两个树完全相同,则返回 `null`。
阅读全文