二叉树-diff算法
简介
本文介绍了如何使用二叉树进行差异比较(diff算法),以确定在两个二叉树之间新增了什么、修改了什么、删除了什么。
实现方法
class Node {
constructor(value) {
this.value = value
this.left = null
this.right = null
}
}
// 创建二叉树的节点 - 1
let a = new Node('a')
let b = new Node('b')
let c = new Node('c')
let d = new Node('d')
let e = new Node('e')
let f = new Node('f')
let g = new Node('g')
// 构建二叉树的结构 - 1
a.left = b
a.right = c
b.left = d
b.right = e
c.left = f
c.right = g
// 创建二叉树的节点 - 2
let a1 = new Node('a')
let b1 = new Node('b')
let c1 = new Node('x') // 修改了c的值为x
let d1 = new Node('d')
let e1 = new Node('e')
let f1 = new Node('f')
let g1 = new Node('g')
let h = new Node('h') // 新增了h
let i = new Node('i') // 新增了i
// 构建二叉树的结构 - 2
a1.left = b1
a1.right = c1
b1.left = d1
b1.right = e1
// c1.left = f1 // 删除了f
c1.right = g1
d1.left = h // 新增了h
e1.left = i // 新增了i
/**
*
* @param {*} root1
* @param {*} root2
* @returns {diffList} [
* {type: 'add', org: null, now: Node},
* {type: 'delete', org: Node, now: null},
* {type: 'update', org: Node1, now: Node2}
* ]
*
*/
function diff(root1, root2, diffList) {
// 如果两个节点都为空,则没有变化
if (root1 === null && root2 === null) return diffList
// 新增
if (root1 === null && root2 !== null) {
diffList.push({ type: 'add', org: null, now: root2 })
// 新增节点的子节点无需递归,直接返回
return diffList
}
// 删除
if (root1 !== null && root2 === null) {
diffList.push({ type: 'delete', org: root1, now: null })
// 删除节点子节点也全部被删除,无需递归,直接返回
return diffList
}
// 修改
if (root1 !== null && root2 !== null && root1.value !== root2.value) {
diffList.push({ type: 'update', org: root1, now: root2 })
// 修改节点的子节点需要递归,继续比较
}
diff(root1.left, root2.left, diffList)
diff(root1.right, root2.right, diffList)
}
let diffList = []
diff(a, a1, diffList)
console.log(diffList)