【算法】二叉树的比较

116 阅读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;

如果要求左子树和右子树严格相等进行比较

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

function compareTree(root1, root2) {
    if(root1 == root2) return true;
    if(root1 == null && root2 != null || root2 == null && root1 != null) return false;
    if(root1.value != root2.value) return false;
    let leftBool = compareTree(root1.left, root2.left);
    let rightBool = compareTree(root1.right, root2.right);
    return leftBool && rightBool;
}
console.log(compareTree(a1, a2))

如果是非严格比较二叉树,左子树和右子树可以互换

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

function compareTree(root1, root2) {
    if(root1 == root2) return true;
    if(root1 == null && root2 != null || root2 == null && root1 != null) return false;
    if(root1.value != root2.value) return false;
    return compareTree(root1.left, root2.left) && compareTree(root1.right, root2.right) 
    || compareTree(root1.left, root2.right) && compareTree(root1.left, root2.right);
}
console.log(compareTree(a1, a2))