JavaScript面向对象,二叉树排序

来源:互联网 发布:钢笔字帖推荐 知乎 编辑:程序博客网 时间:2024/06/06 04:34
<SCRIPT LANGUAGE="JavaScript">
 
function node(data) ...{
        
this.data=data;
        
var Lnode;
        
var Rnode; 
        
this.insert=function insert(newData) ...{
                
if(newData<this.data)...{
                        
ifthis.Lnode==null...{
                                
this.Lnode=new node(newData);
                        }

                        
else ...{
                              
this.Lnode.insert(newData);
                        }

                }

                
else ...{
                        
if(this.Rnode==null...{
                                
this.Rnode=new node(newData); 
                        }

                        
else ...{
                                
this.Rnode.insert(newData);
                      }

                }

        }

}


function tree() ...
        
var root ; 
        
this.insertNode=function insertNode(newData) ...{  
                
if(this.root==null...{
                        
this.root=new node(newData);
                        
this.index=0;
                }

              
else ...{
                        
this.root.insert(newData); 
                }

        }
  
        
this.inOrderTraversal=function inOrderTraversal() ...{    //中序便历
              this.inOrder(this.root); 
        }

        
this.inOrder=function inOrder(N) ...{
                
if (N!=null...{
                      
//document.write("test data is:"+N.data + "&nbsp;<br>");
                        this.inOrder(N.Lnode);
                        
//输出结果
                        document.write(N.data + "&nbsp;");
                        
this.inOrder(N.Rnode); 
                        
//document.write("out is"+N.data+"<br>");
                    //document.write(N.data + "&nbsp;");
                }

        }

}


//test随便插入一些数字进来。0
  
var T=new tree() 
T.insertNode( 
40);
T.insertNode( 
39);
T.insertNode( 
69);
T.insertNode( 
94);
T.insertNode( 
47);
T.insertNode( 
50);
T.insertNode( 
72);
T.insertNode( 
55);
T.insertNode( 
41);
T.insertNode( 
97);
T.insertNode( 
73);
T.insertNode( 
10);
T.insertNode( 
56);
T.inOrderTraversal(); 
</SCRIPT>
<br>
非常经典,面向对象的特性运用很好
 
原创粉丝点击