【前端】自学基础算法 -- 13.二叉树-diff算法

二叉树-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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值