zoukankan      html  css  js  c++  java
  • JavaScript实现二叉查找树

    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;
    }
    }

  • 相关阅读:
    HDU 2098 分拆素数和
    HDU 2034 *人见人爱A-B
    HDU 1236 排名(Microsoft_zzt)
    HDU 5702 Solving Order
    HDU 2033 人见人爱A+B
    HDU 2029 Palindromes _easy version
    HDU 2021 发工资咯:)
    HDU 2071 Max Num
    HDU 2039 三角形
    页面使用element-tree
  • 原文地址:https://www.cnblogs.com/aobama/p/4347010.html
Copyright © 2011-2022 走看看