Javascript search Binary Tree

Source: Internet
Author: User

Javascript search Binary Tree

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; // This is easy to ignore, And the next sentence if is missing to judge current. data will report an error.} 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 ;}},/* First traverse */firstlist: function (root) {if (root! = Null) {console. log (root. data); this. firstlist (root. left); this. firstlist (root. right) ;}},/* sequential traversal */lastlist: function (root) {if (root! = Null) {this. lastlist (root. left); this. lastlist (root. right); console. log (root. data) ;}},/* sequential traversal */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 );


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.