您的位置:首页 > 理论基础 > 数据结构算法

数据结构与算法JavaScript - 二叉树和二叉查找树

2016-07-28 18:01 549 查看


是计算机科学中常用到的一种数据结构。

是一种非线性的数据结构,以分层的方式存储数据。

被用来存储具有层级关系的数据。

二叉树: 二叉树是一种特殊的树,对二叉树进行查找非常快,为二叉树添加或删除元素也非常快。

树的定义

树由一组以边连接的节点组成,自上而下的层级顺序。

一棵树上最上面的节点称为根节点,如果一个节点下面连接多个节点,那么该节点称为父节点,它下面的称为子节点。

一个节点可以有0个、1个或多个子节点。没有子节点的节点称为叶子节点。

二叉树的子节点个数不超过两个

一个父节点的两个子节点分别称为左节点和右节点。

二叉查找树是一种特殊的二叉树,相对较小的值存储在左节点中,较大的值保存在右节点中。

二叉查找树的构造函数

在二叉查找树中,要执行
insert()
方法进行数据的插入。

遍历二叉查找树的方法有:中序,先序,后序

中序:按照节点上的键值,以升序访问BST上的所有节点(左-根-右);

先序:先访问根节点,然后以同样方式访问左子树和右子树(根-左-右);

后序:先访问叶子节点,从左子树到右子树,再到根节点(左-右-根)。

构造函数如下:

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;
this.preOrder = preOrder;
this.postOrder = postOrder;
}

function insert(data) {
var n = new Node(data, null, null);
if (this.root == null) {
this.root = null;
}
else {
var current = this.root;
var parent;
while (true) {
parent = current;
if (data < current.data) {
current = current.left;
if (current == 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);
putstr(node.show() + " ");
inOrder(node.right);
}
}

//先序遍历
function preOrder() {
if (!(node == null)) {
putstr(node.show() + " ");
preOrder(node.left);
preOrder(node.right);
}
}

// 后序遍历
function postOrder() {
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;
}

function remove(data) {
root = removeNode(this.root, data);
}

function removeNode(node, data) {
if (node == null) {
return null;
}
if (data == node.data) {
// no subnode
if (node.left == null && node.right == null) {
return null;
}
// no left subnode
if (node.left == null) {
return node.right;
}
// no right subnode
if (node.right == null) {
return node.right;
}
// have two subnode
var tempNode = getSmallest(node.right);
node.data = tempNode.data;
node.right = removeNode(node.right, tempNode.data);
return node;
}
else if (data < node.data) {
node.left = removeNode(node.left, data);
return node;
}
else {
node.right = removeNode(node.right, data);
return node;
}
}


关于二叉查找树,这片文章还不错:https://segmentfault.com/a/1190000000740261
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息