JS 树

定义

  • 一棵树最上面的节点称之为根节点
  • 如果一棵树下面有多个节点,那么该节点称之为父节点
  • 父节点下面的节点称之为子节点
  • 一个子节点到另外一个子节点的路线称之为路径
  • 按照某种特定顺序访问节点称之为树的遍历
  • 每个节点与之相关的值称之为键

二叉树

它是一种特殊的树

  • 它的节点个数不超过2个
  • 具有一些特殊的性质,操作特别的高效
  • 一个父节点的两个子节点,左边的叫左节点,右边的叫右节点

二叉查找树

一种特殊的二叉树

  • 若左子树不空,则左子树上所有结点的值均小于它的根结点的值
  • 若右子树不空,则右子树上所有结点的值均大于它的根结点的值
  • 左、右子树也分别为二叉排序树;
  • 没有键值相等的节点

遍历方式

  • 中序:按照节点键值,以升序的方式遍历树所有节点
  • 先序:先访问根节点,然后在以同样的方式访问左子树和右子树
  • 后序:先访问子节点,从左子树到右子树,最后访问根节点

查找方式

  • 查找给定值
  • 查找最小值
  • 查找最大值

例子

function Node(data, left, right) {
    this.data = data;
    this.left = left;
    this.right = right;
    this.show = show;
}

// 二叉树
function BTS() {
    this.root = null;
    this.insert = insert;
    this.inOrder = inOrder;
    this.preOrder = preOrder;
    this.postOrder = postOrder;

    this.getMax = getMax;
    this.getMin = getMin;
    this.find = find;

}


function show() {
    return this.data;
}

function insert(data) {
    var newNode = new Node(data, null, null);
    // 1:检查当前树是否有根节点
    if (this.root == null) {
        this.root = newNode;
        return;
    }
    // 2:如果该树有根节点,那么就遍历
    var current = this.root;
    var parent;
    while (true) {
        parent = current;
        if (data < current.data) {
            current = current.left;
            if (current == null) {
                parent.left = newNode;
                break;
            }
        } else {
            current = current.right;
            if (current == null) {
                parent.right = newNode
                break;
            }
        }
    }

}

// 中序遍历,递归查询,所有节点从小到大
function inOrder(node) {
    if (node != null) {
        inOrder(node.left);
        console.log(node.show() + " ");
        inOrder(node.right)
    }
}
// 先序,先从根节点,从
function preOrder(node) {
    if (!(node == null)) {
        putstr(node.show() + " ");
        preOrder(node.left);
        preOrder(node.right);
    }
}

// 后序
function postOrder(node) {
    if (!(node == null)) {
        postOrder(node.left);
        postOrder(node.right);
        putstr(node.show() + " ");
    }
}

// 查找最小值
function getMin() {
    var current = this.root;
    while (current.left != null) {
        current = current.left;
    }
    return current.data;
}
// 查找最大值
function getMax() {
    var current = this.root;
    while (!(current.right == null)) {
        current = current.right;
    }

    return current.data;
}

// 查找给定值
function find(data) {
    var current = this.root;
    while (current != null) {
        if (current.data == data) {
            return current;
        }
        else if (data < current.data) {
            current = current.left;
        } else {
            current = current.right;
        }
    } return null;
}
原文地址:https://www.cnblogs.com/dark-liu/p/5830988.html