JavaScript實現二叉尋找樹

來源:互聯網
上載者:User

標籤:

function Node(data, left, right) //定義二叉樹節點,包括節點上儲存的資料,指向左右子節點的指標
{
this.data = data;
this.left = left;
this.right = right;
this.show = show;
}


function show() {
return this.data;
}

 

function BST() {
this.root = null;
this.insert = insert;
this.inOrder = inOrder;
}


function insert(data) {
var n = new Node(data, null, null);
if (this.root == null) {
this.root = n;
}
else {
var current = this.root;
var parent;
while (true) {
parent = current;
if (data < current.data) {
current = current.left;
if (current.left == null) {
parent.left = n;
break;
}
}
else {
current = current.right;
if (current == null) {
parent.right = n;
break;
}
}
}
}
}

 

 


function inOrder(node) {
if (node != null) {
inOrder(node.left);
print(node.show());
inOrder(node.right);
}
}


function preOrder(node) {
if (node != null) {
print(node.show());
preOrder(node.left);
preOrder(node.rigth);
}
}


function postOrder(node) {
if (node != null) {
postOrder(node.left);
postOrder(node.right);
print(node.show());
}
}

 


function getMin() {
var current = this.root;
if (current == null) {
return false;
}
while (!(current.left == null)) {
current = current.left;
}
return current.data;
}


function getMan() {

var current = this.root;
if (current == null) {
return false;
}
while (!(current.right == null)) {
current = current.right;
}
return current.data;
}


function findData(data) {
var current = this.root;
while (!(current== null)) {
if (current.data == data) {
return true;
}
else if (current.data > data) {
current = current.left;
}
else
{
current = current.right;
}
return false;
}
}

 

JavaScript實現二叉尋找樹

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.