Are simple things, so go directly to the code.
/** * Created by Huangjacky on 14-10-3. */function Node (element, left, right) {this.element = element; This.level = 0; This.left = left; This.right = right;} function BST () {this.root = null;} Bst.prototype = {Insert:function (element) {var n = new Node (element, NULL, NULL); if (this.root = = null) {this.root = n; N.level = 0; return true; } else {var current = This.root; var parent = null; while (current! = null) {if (element < current.element) {parent = current; current = Current.left; } else if (element > current.element) {parent = current; current = Current.right; } else {return false; }} n.level = Parent.level + 1; if (element < parent.element) {Parent.left =N } else {parent.right = n; } return true; }}, Tostring:function () {return This.inorder (this.root, function (n) {return "\ t" + N.element + ' (' + n.level + ') \ t "; }); }, Inorder:function (n, FN) {//middle order traversal if (!n) {return '; } else {return This.inorder (N.left, FN) + fn (n) + this.inorder (N.right, FN); }}, Preorder:function (n, FN) {////ordinal traversal if (!n) {return '; } else {return fn (n) + this.preorder (N.left, FN) + this.preorder (N.right, FN); }}, Postorder:function (n, FN) {//post-traverse if (!n) {return '; } else {return This.postorder (N.left, FN) + this.postorder (N.right, FN) + FN (n); }}};var A = new BST (); A.insert (3); A.insert (1); A.insert (5); A.insert (2); A.insert (4); Console.log ("inorder:" + A.tostrin g ()); var fn = function (n) {return ' \ t ' + n.element + ' (' + n.level + ') \ t ";}; var S1 = a.preorder (A.root, FN), var s2 = a.postorder (A.root, FN), Console.log ("Pre Order:" + S1); Console.log ("Post order:" + s2);
JavaScript-Two fork Tree