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),或者是一棵空樹,或者是具有下列性質的二叉樹: 若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值; 若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值; 它的左、右子樹也分別為二叉排序樹。
所以不一定是