比较两个子树的不同之处 此处并没有比较走右子树互换的情况
const Node = require("../common")
// 二叉树1
let a1 = new Node('a');
let b1 = new Node('b');
let c1 = new Node('c');
let d1 = new Node('d');
let e1 = new Node('e');
let f1 = new Node('f');
let g1 = new Node('g');
a1.left = c1;
c1.left = f1;
b1.left = d1;
a1.right = b1;
b1.right = e1;
c1.right = g1;
// 二叉树2
let a2 = new Node('a');
let b2 = new Node('b');
let c2 = new Node('c');
let d2 = new Node('d');
let e2 = new Node('e');
let f2 = new Node('f');
let g2 = new Node('g');
a2.left = c2;
c2.left = f2;
b2.left = d2;
a2.right = b2;
b2.right = e2;
c2.right = g2;
/**
*两个二叉树那里不同,不同之处在哪
* @param {*} root1 二叉树1
* @param {*} root2 二叉树2
* @param {*} diffList 不同列表
* @returns
* [
* 第一种情况
* {type:"新增",origin:"null",now:"null",}
* 第二种情况
* {type:"删除",origin:"null",now:"null",}
* 第三种情况
* {type:"替换",origin:"null",now:"null",}
* ]
*/
function compareDiffTree(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, })
compareDiffTree(root1.left, root2.left, diffList)
compareDiffTree(root1.right, root2.right, diffList)
} else {
compareDiffTree(root1.left, root2.left, diffList)
compareDiffTree(root1.right, root2.right, diffList)
}
}
var diffList = [];
compareDiffTree(a1, a2,diffList)
console.log(diffList)
导入的common.js
module.exports = class Node{
constructor(value){
this.value = value;
this.left = null;
this.right = null;
}
}