嚴格比較二叉樹,左子樹和右子樹嚴格相等: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1 ...
嚴格比較二叉樹,左子樹和右子樹嚴格相等:
<!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.left = b; a.right = c; b.left = d; b.right = e; c.left = f; c.right = g; //嚴格比較二叉樹,左子樹和右子樹必須完全一樣,不可互換 function compareTree(root1, root2){ if(root1 == root2) return true;//兩棵樹是同一棵樹 if((root1 == null && root2 != null) || (root1 != null && root2 == null)) return false;//兩棵樹有一棵為null,另一棵不是null if(root1.value != root2.value) return false;//節點的值不同 var leftBoolean = compareTree(root1.left, root2.left);//比較左子樹 var rightBoolean = compareTree(root1.right, root2.right);//比較右子樹 return leftBoolean && rightBoolean;//左子樹和右子樹必須都一樣 } console.log(compareTree(nodeA, a)); </script> </body> </html>嚴格比較二叉樹
非嚴格比較二叉樹,左子樹和右子樹可以互換:
<!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; //非嚴格比較二叉樹,左子樹和右子樹可互換 function compareTree(root1, root2){ if(root1 == root2) return true;//兩棵樹是同一棵樹 if((root1 == null && root2 != null) || (root1 != null && root2 == null)) return false;//兩棵樹有一棵為null,另一棵不是null if(root1.value != root2.value) return false;//節點的值不同 return (compareTree(root1.left, root2.left) && compareTree(root1.right, root2.right) || compareTree(root1.right, root2.left) && compareTree(root1.left, root2.right));//左子樹和右子樹可以互換 } console.log(compareTree(nodeA, a)); </script> </body> </html>非嚴格比較二叉樹