function Node(data, left, right) { this.data = data; this.count = 1; this.left = left; this.right = right; this.show = show; } function show() { return this.data; } function BST() { this.root = null; this.insert = insert; this.find = find; this.insert = insert; this.update = update; } function insert(data) { var n = new Node(data, null, null); if (this.root == null) { this.root = n; } else { var current = this.root; var parent; while (true) { parent = current; if (data < current.data) { current = current.left; if (current == null) { parent.left = n; break; } } else { current = current.right; if (current == null) { parent.right = n; break; } } } } } function find(data) { var current = this.root; while (current != null) { if (current.data == data) { return current; } else if (data < current.data) { current = current.left; } else { current = current.right; } } return null; } function update(data) { var grade = this.find(data); grade.count++; return grade; } function prArray(arr) {//每行十个元素显示数组中元素 for ( var i = 0; i < arr.length; ++i) { document.write(arr[i] + " "); if ((i + 1) % 10 == 0) { document.write("<br /> "); } } } function genArray(length) {//产生指定元素个数的数组 var arr = []; for ( var i = 0; i < length; ++i) { arr[i] = Math.floor(Math.random() * 101); } return arr; } var grades = genArray(100); prArray(grades); var gradedistro = new BST(); for ( var i = 0; i < grades.length; ++i) {//将数组中元素添加到二叉树中 var g = grades[i]; var grade = gradedistro.find(g); if (grade == null) { gradedistro.insert(g); } else { gradedistro.update(g); } } document.write("*************** " + "<br />"); var g = 45; var aGrade = gradedistro.find(g); if (aGrade == null) { document.write("No occurrences of " + g); } else { document.write("Occurrences of " + g + ": " + aGrade.count); }
时间: 2024-10-22 00:16:20