8.二叉树的diff算法,查看并输出二叉树不同的地方(JavaScript版)
Posted lanshanxiao
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了8.二叉树的diff算法,查看并输出二叉树不同的地方(JavaScript版)相关的知识,希望对你有一定的参考价值。
查看并输出二叉树不同的地方:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <script> function Node(value) { this.value = value; this.left = null; this.right = null; } var nodeA = new Node("a"); var nodeB = new Node("b"); var nodeC = new Node("c"); var nodeD = new Node("d"); var nodeE = new Node("e"); var nodeF = new Node("f"); var nodeG = new Node("g"); nodeA.left = nodeB; nodeA.right = nodeC; nodeB.left = nodeD; nodeB.right = nodeE; nodeC.left = nodeF; nodeC.right = nodeG; var a = new Node("a"); var b = new Node("b"); var c = new Node("c"); var d = new Node("d"); var e = new Node("e"); var f = new Node("f"); var g = new Node("g"); a.right = b; a.left = c; b.left = d; b.right = e; c.left = f; c.right = g; //要找到两个二叉树之间有什么不同 //1.新增了节点 //2.删除了节点 //3.修改了节点 //不同的地方,存入diffList中 function diffTree(root1, root2, diffList) { var diff = diffList || []; if (root1 == root2) return diff; //若两者是同一颗树,则直接返回diff if (root1 == null && root2 != null) { //root2新增了一个节点 diff.push({ type: "新增", origin: null, new: root2 }); } else if (root1 != null && root2 == null) { //root2删除了一个节点 diff.push({ type: "删除", origin: root1, new: null }); } else if (root1.value != root2.value) { //root2节点的值被修改了 diff.push({ type: "修改", origin: root1.value, new: root2.value }); //二叉树的节点值被修改,还需要再次判断子节点 diffTree(root1.left, root2.left, diff); //判断左子树 diffTree(root1.right, root2.right, diff); //判断右子树 } else { diffTree(root1.left, root2.left, diff); //判断左子树 diffTree(root1.right, root2.right, diff); //判断右子树 } return diff; } var diffList = []; var diff = diffTree(nodeA, a, diffList); console.log(diff); </script> </body> </html>
以上是关于8.二叉树的diff算法,查看并输出二叉树不同的地方(JavaScript版)的主要内容,如果未能解决你的问题,请参考以下文章