码迷,mamicode.com
首页 > 编程语言 > 详细

javascript 搜索二叉树

时间:2014-10-17 18:51:23      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:blog   io   ar   java   2014   on   cti   log   ad   

   function Tree() {
     this.root = null;
   }
   Tree.prototype = {
     constructor: Tree,
     addItem: function(value) {
       var Node = {
         data: value,
         left: null,
         right: null
       };
       if (this.root == null) {
         this.root = Node;
       } else {
         var current = this.root;
         var parent = current;
         while (current !== null) {
           parent = current;
           if (value < current.data) {
             current = current.left;
             continue; //此处容易忽略,缺少下一句if判断current.data会报错
           }
           if (value === current.data) {
             return false;
           }
           if (value > current.data) {
             current = current.right;
             continue;
           }
         }
         if (value < parent.data) {
           parent.left = Node;
         }
         if (value > parent.data) {
           parent.right = Node;
         }
       }
     },
     /*先序遍历*/
     firstlist: function(root) {
       if (root !== null) {
         console.log(root.data);
         this.firstlist(root.left);
         this.firstlist(root.right);
       }
     },
     /*后序遍历*/
     lastlist: function(root) {
       if (root !== null) {
         this.lastlist(root.left);
         this.lastlist(root.right);
         console.log(root.data);
       }
     },
     /*中序遍历*/
     inlist: function(root) {
       if (root !== null) {
         this.inlist(root.left);
         console.log(root.data);
         this.inlist(root.right);
       }
     }
   };
   var Tree = new Tree();
   Tree.addItem(5);
   Tree.addItem(1);
   Tree.addItem(6);
   Tree.addItem(8);
   Tree.addItem(7);


javascript 搜索二叉树

标签:blog   io   ar   java   2014   on   cti   log   ad   

原文地址:http://blog.csdn.net/primary_wind/article/details/40188727

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!