比较两个子树的不同之处 此处并没有比较走右子树互换的情况
    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. * @param {*} diffList 不同列表
    35. * @returns
    36. * [
    37. * 第一种情况
    38. * {type:"新增",origin:"null",now:"null",}
    39. * 第二种情况
    40. * {type:"删除",origin:"null",now:"null",}
    41. * 第三种情况
    42. * {type:"替换",origin:"null",now:"null",}
    43. * ]
    44. */
    45. function compareDiffTree(root1, root2, diffList = []) {
    46. if (root1 == root2) return diffList;
    47. if (root1 == null && root2 != null) {
    48. diffList.push({ type: "新增", origin: "null", now: root2, })
    49. } else if (root1 != null && root2 == null) {
    50. diffList.push({ type: "删除", origin: root1, now: "null", })
    51. } else if (root1.value != root2.value) {
    52. diffList.push({ type: "替换", origin: root1, now: root2, })
    53. compareDiffTree(root1.left, root2.left, diffList)
    54. compareDiffTree(root1.right, root2.right, diffList)
    55. } else {
    56. compareDiffTree(root1.left, root2.left, diffList)
    57. compareDiffTree(root1.right, root2.right, diffList)
    58. }
    59. }
    60. var diffList = [];
    61. compareDiffTree(a1, a2,diffList)
    62. console.log(diffList)

    导入的common.js

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