function Tree(){ this.root=null } function Node(v){ this.val=[v] this.left=null this.right=null } Node.prototype.Add=function(n){ if(this.val[0]>n.val[0]){2 if(this.left!=null){ this.left.Add(n) }else{ this.left=n } }else if(this.val[0]<n.val[0]){ if(this.right!=null){ this.right.Add(n) }else{ this.right=n } }else{ this.val.push(n.val[0]) } } Tree.prototype.Add=function(v){ var node =new Node(v) if(this.root==null){ this.root=node }else{ this.root.Add(node) } } var tree=new Tree() for(var i=0;i<20;i++){ tree.Add(Math.ceil(Math.random()*100)) } var d=[] var preOrder = function (node) { if (node) { preOrder(node.left); d.push(...node.val) preOrder(node.right); } } preOrder(tree.root) console.log(d)
二叉树排序