javascript 搜尋二叉樹,javascript二叉樹

來源:互聯網
上載者:User

javascript 搜尋二叉樹,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; //此處容易忽略,缺少下一句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 可以寫二叉樹

自己想吧,用軟體不好。 看看遍曆有沒有問題。
 
二叉搜尋樹是完全二叉樹

二叉尋找樹(Binary Search Tree),或者是一棵空樹,或者是具有下列性質的二叉樹: 若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值; 若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值; 它的左、右子樹也分別為二叉排序樹。

所以不一定是
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.