【算法】二叉树的diff算法

140 阅读1分钟
function Tree(value) {
	this.value = value;
	this.left = null;
	this.right = null;
}
const a1 = new Tree("A")
const b1 = new Tree("B")
const c1 = new Tree("C")
const d1 = new Tree("D")
const e1 = new Tree("E")
const f1 = new Tree("F")
const g1 = new Tree("G")

const a2 = new Tree("A")
const b2 = new Tree("B")
const c2 = new Tree("C")
const d2 = new Tree("D")
const e2 = new Tree("E")
const f2 = new Tree("F")
const g2 = new Tree("G")

a1.left = b1;
a1.right = c1;
b1.left = d1;
b1.right = e1;
c1.left = f1;
c1.right = g1;

a2.left = b2;
a2.right = c2;
b2.left = d2;
b2.right = e2;
c2.left = f2;
c2.right = g2;

function diffTree(root1, root2, diffList) {
	if(root1 == root2) return diffList;
	if(root1 == null && root2 != null) {
		diffList.push({type: "新增", origin: null, now: root2})
	} else if(root1 != null && root2 == null) {
		diffList.push({type: "删除", origin: root1, now: null})
	} else if(root1.value != root2.value) {
		diffList.push({type: "修改", origin: root1, now: root2})
		diffTree(root1.left, root2.left, diffList);
		diffTree(root1.right, root2.right, diffList);
	} else {
		diffTree(root1.left, root2.left, diffList);
		diffTree(root1.right, root2.right, diffList);
	}
}
let diffList = [];
diffTree(a1, a2, diffList);
console.log(diffList)
// [
// 	{
// 		type: "新增",
// 		origin: origin,
// 		now: now
// 	}, 
// 	{
// 		type: "删除",
// 		origin: origin,
// 		now: now
// 	},
// 	{
// 		type: "修改",
// 		origin: origin,
// 		now: now
// 	},
// ]

截屏2022-05-21 上午2.02.52.png

截屏2022-05-21 上午2.03.01.png

截屏2022-05-21 上午2.03.12.png