比对两个二叉树,判断两个二叉树是否完全相等
    如下图
    image.png

    1. const Node = require("../common")
    2. // 二叉树1
    3. let a1 = new Node('a');
    4. let b1 = new Node('b');
    5. let c1 = new Node('c');
    6. let d1 = new Node('d');
    7. let e1 = new Node('e');
    8. let f1 = new Node('f');
    9. let g1 = new Node('g');
    10. a1.left = c1;
    11. c1.left = f1;
    12. b1.left = d1;
    13. a1.right = b1;
    14. b1.right = e1;
    15. c1.right = g1;
    16. // 二叉树2
    17. let a2 = new Node('a');
    18. let b2 = new Node('b');
    19. let c2 = new Node('c');
    20. let d2 = new Node('d');
    21. let e2 = new Node('e');
    22. let f2 = new Node('f');
    23. let g2 = new Node('g');
    24. a2.left = c2;
    25. c2.left = f2;
    26. b2.left = d2;
    27. a2.right = b2;
    28. b2.right = e2;
    29. c2.right = g2;
    30. /**
    31. * 二叉树左右子树无交换的比较
    32. * @param {*} root1 二叉树1
    33. * @param {*} root2 二叉树2
    34. */
    35. function compareTree(root1, root2) {
    36. if (root1 == root2) return true;
    37. if (root1 != null && root2 == null || root1 == null && root2 != null) return false;
    38. if (root1.value != root2.value) return false;
    39. let left = compareTree(root1.left, root2.left)
    40. let right = compareTree(root1.right, root2.right)
    41. return left && right
    42. }
    43. console.log(compareTree(a1,a2))

    导入的common.js

    1. module.exports = class Node{
    2. constructor(value){
    3. this.value = value;
    4. this.left = null;
    5. this.right = null;
    6. }
    7. }