zoukankan      html  css  js  c++  java
  • javascript 搜索二叉树

       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; //此处easy忽略,缺少下一句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);


  • 相关阅读:
    python
    mysql 操作
    you-get 使用代理
    恢复本地策略组--用于启动项管理等
    bat批处理——获取文件夹下所有文件名/重命名
    cmd--set用法,下次补充实例
    bat+7z批量压缩"文件夹"
    Excel提取字符串示例
    cron
    AIX修改用户密码登录不成功案例分享
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/5412160.html
Copyright © 2011-2022 走看看