JavaScript 数据结构与算法之美 - 非线性表中的树、堆是干嘛用的 ?其数据结构是怎样的 ?(下)

简介: JavaScript 数据结构与算法之美 - 非线性表中的树、堆是干嘛用的 ?其数据结构是怎样的 ?(下)

二叉树的遍历


经典的方法有三种:前序遍历、中序遍历、后序遍历。其中,前、中、后序,表示的是节点与它的左右子树节点遍历访问的先后顺序。


前序遍历(根 => 左 => 右)


  • 对于树中的任意节点来说,先访问这个节点,然后再访问它的左子树,最后访问它的右子树。


中序遍历(左 => 根 => 右)


  • 对于树中的任意节点来说,先访问它的左子树,然后再访问它的本身,最后访问它的右子树。


后序遍历(左 => 右 => 根)


  • 对于树中的任意节点来说,先访问它的左子树,然后再访问它的右子树,最后访问它本身。


实际上,二叉树的前、中、后序遍历就是一个递归的过程。


微信图片_20220513110053.png


时间复杂度:3 种遍历方式中,每个节点最多会被访问 2 次,跟节点的个数 n 成正比,所以时间复杂度是 O(n)。


实现二叉查找树


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

代码实现二叉查找树,方法有以下这些。


方法


  • insert(key):向树中插入一个新的键。
  • search(key):在树中查找一个键,如果节点存在,则返回 true;如果不存在,则返回 false。
  • min:返回树中最小的值/键。
  • max:返回树中最大的值/键。
  • remove(key):从树中移除某个键。


遍历


  • preOrderTraverse:通过先序遍历方式遍历所有节点。
  • inOrderTraverse:通过中序遍历方式遍历所有节点。
  • postOrderTraverse:通过后序遍历方式遍历所有节点。


具体代码


  • 首先实现二叉查找树类的类


// 二叉查找树类
function BinarySearchTree() {
    // 用于实例化节点的类
    var Node = function(key){
        this.key = key; // 节点的健值
        this.left = null; // 指向左节点的指针
        this.right = null; // 指向右节点的指针
    };
    var root = null; // 将根节点置为null
}


  • insert 方法,向树中插入一个新的键。


遍历树,将插入节点的键值与遍历到的节点键值比较,如果前者大于后者,继续递归遍历右子节点,反之,继续遍历左子节点,直到找到一个空的节点,在该位置插入。


this.insert = function(key){
    var newNode = new Node(key); // 实例化一个节点
    if (root === null){
        root = newNode; // 如果树为空,直接将该节点作为根节点
    } else {
        insertNode(root,newNode); // 插入节点(传入根节点作为参数)
    }
};
// 插入节点的函数
var insertNode = function(node, newNode){
    // 如果插入节点的键值小于当前节点的键值
    // (第一次执行insertNode函数时,当前节点就是根节点)
    if (newNode.key < node.key){
        if (node.left === null){
            // 如果当前节点的左子节点为空,就直接在该左子节点处插入
            node.left = newNode;
        } else {
            // 如果左子节点不为空,需要继续执行insertNode函数,
            // 将要插入的节点与左子节点的后代继续比较,直到找到能够插入的位置
            insertNode(node.left, newNode);
        }
    } else {
        // 如果插入节点的键值大于当前节点的键值
        // 处理过程类似,只是insertNode函数继续比较的是右子节点
        if (node.right === null){
            node.right = newNode;
        } else {
            insertNode(node.right, newNode);
        }
    }
}


在下图的树中插入健值为 6 的节点,过程如下:


微信图片_20220513110154.png


  • 搜索最小值


在二叉搜索树里,不管是整个树还是其子树,最小值一定在树最左侧的最底层。

因此给定一颗树或其子树,只需要一直向左节点遍历到底就行了。


this.min = function(node) {
    // min方法允许传入子树
    node = node || root;
    // 一直遍历左侧子节点,直到底部
    while (node && node.left !== null) {
        node = node.left;
    }
    return node;
};


  • 搜索最大值


搜索最大值与搜索最小值类似,只是沿着树的右侧遍历。


this.max = function(node) {
    // min方法允许传入子树
    node = node || root;
    // 一直遍历左侧子节点,直到底部
    while (node && node.right !== null) {
        node = node.right;
    }
    return node;
};


  • 搜索特定值


搜索特定值的处理与插入值的处理类似。遍历树,将要搜索的值与遍历到的节点比较,如果前者大于后者,则递归遍历右侧子节点,反之,则递归遍历左侧子节点。


this.search = function(key, node){
    // 同样的,search方法允许在子树中查找值
    node = node || root;
    return searchNode(key, node);
};
var searchNode = function(key, node){
    // 如果node是null,说明树中没有要查找的值,返回false
    if (node === null){
        return false;
    }
    if (key < node.key){
        // 如果要查找的值小于该节点,继续递归遍历其左侧节点
        return searchNode(node.left, key);
    } else if (key > node.key){
        // 如果要查找的值大于该节点,继续递归遍历其右侧节点
        return searchNode(node.right, key);
    } else {
        // 如果要查找的值等于该节点,说明查找成功,返回改节点
        return node;
    }
};


  • 移除节点


移除节点,首先要在树中查找到要移除的节点,再判断该节点是否有子节点、有一个子节点或者有两个子节点,最后分别处理。


this.remove = function(key, node) {
    // 同样的,允许仅在子树中删除节点
    node = node || root;
    return removeNode(key, node);
};
var self = this;
var removeNode = function(key, node) {
    // 如果 node 不存在,直接返回
    if (node === false) {
        return null;
    }
    // 找到要删除的节点
    node = self.search(key, node);
    // 第一种情况,该节点没有子节点
    if (node.left === null && node.right === null) {
        node = null;
        return node;
    }
    // 第二种情况,该节点只有一个子节点的节点
    if (node.left === null) {
        // 只有右节点
        node = node.right;
        return node;
    } else if (node.right === null) {
        // 只有左节点
        node = node.left;
        return node;
    }
    // 第三种情况,有有两个子节点的节点
    // 将右侧子树中的最小值,替换到要删除的位置
    // 找到最小值
    var aux = self.min(node.right);
    // 替换
    node.key = aux.key;
    // 删除最小值
    node.right = removeNode(aux.key, node.right);
    return node;
};


第三种情况的处理过程,如下图所示。


当要删除的节点有两个子节点时,为了不破坏树的结构,删除后要替补上来的节点的键值大小必须在已删除节点的左、右子节点的键值之间,且替补上来的节点不应该有子节点,否则会产生一个节点有多个字节点的情况,因此,找右侧子树的最小值替换上来。

同理,找左侧子树的最大值替换上来也可以。


微信图片_20220513110257.png


  • 先序遍历


this.preOrderTraverse = function(callback){
    // 同样的,callback用于对遍历到的节点做操作
    preOrderTraverseNode(root, callback);
};
var preOrderTraverseNode = function (node, callback) {
    // 遍历到node为null为止
    if (node !== null) {
        callback(node.key); // 先处理当前节点
        preOrderTraverseNode(node.left, callback); // 再继续遍历左子节点
        preOrderTraverseNode(node.right, callback); // 最后遍历右子节点
    }
};


用先序遍历遍历下图所示的树,并打印节点键值。


输出结果:11 7 5 3 6 9 8 10 15 13 12 14 20 18 25。

遍历过程如图:


微信图片_20220513110320.png


  • 中序遍历


this.inOrderTraverse = function(callback){
    // callback用于对遍历到的节点做操作
    inOrderTraverseNode(root, callback);
};
var inOrderTraverseNode = function (node, callback) {
    // 遍历到node为null为止
    if (node !== null) {
        // 优先遍历左边节点,保证从小到大遍历
        inOrderTraverseNode(node.left, callback);
        // 处理当前的节点
        callback(node.key);
        // 遍历右侧节点
        inOrderTraverseNode(node.right, callback);
    }
};


对下图的树做中序遍历,并输出各个节点的键值。


依次输出:3 5 6 7 8 9 10 11 12 13 14 15 18 20 25。

遍历过程如图:


微信图片_20220513110352.png


  • 后序遍历


this.postOrderTraverse = function(callback){
    postOrderTraverseNode(root, callback);
};
var postOrderTraverseNode = function (node, callback) {
    if (node !== null) {
        postOrderTraverseNode(node.left, callback); //{1}
        postOrderTraverseNode(node.right, callback); //{2}
        callback(node.key); //{3}
    }
};


可以看到,中序、先序、后序遍历的实现方式几乎一模一样,只是 {1}、{2}、{3} 行代码的执行顺序不同。


对下图的树进行后序遍历,并打印键值:3 6 5 8 10 9 7 12 14 13 18 25 20 15 11。

遍历过程如图:


微信图片_20220513110421.png


  • 添加打印的方法 print。


this.print = function() {
  console.log('root :', root);
  return root;
};


完整代码请看文件 binary-search-tree.html

测试过程:


// 测试
var binarySearchTree = new BinarySearchTree();
var arr = [11, 7, 5, 3, 6, 9, 8, 10, 15, 13, 12, 14, 20, 18, 25];
for (var i = 0; i < arr.length; i++) {
    var value = arr[i];
    binarySearchTree.insert(value);
}
console.log('先序遍历:');
var arr = [];
binarySearchTree.preOrderTraverse(function(value) {
    // console.log(value);
    arr.push(value);
});
console.log('arr :', arr); // [11, 7, 5, 3, 6, 9, 8, 10, 15, 13, 12, 14, 20, 18, 25]
var min = binarySearchTree.min();
console.log('min:', min); // 3
var max = binarySearchTree.max();
console.log('max:', max); // 25
var search = binarySearchTree.search(10);
console.log('search:', search); // 10
var remove = binarySearchTree.remove(13);
console.log('remove:', remove); // 13
console.log('先序遍历:');
var arr1 = [];
binarySearchTree.preOrderTraverse(function(value) {
    // console.log(value);
    arr1.push(value);
});
console.log('arr1 :', arr1); //  [11, 7, 5, 3, 6, 9, 8, 10, 15, 14, 12, 20, 18, 25]
console.log('中序遍历:');
var arr2 = [];
binarySearchTree.inOrderTraverse(function(value) {
    // console.log(value);
    arr2.push(value);
}); 
console.log('arr2 :', arr2); // [3, 5, 6, 7, 8, 9, 10, 11, 12, 14, 15, 18, 20, 25]
console.log('后序遍历:');
var arr3 = [];
binarySearchTree.postOrderTraverse(function(value) {
    // console.log(value);
    arr3.push(value);
});
console.log('arr3 :', arr3); //  [3, 6, 5, 8, 10, 9, 7, 12, 14, 18, 25, 20, 15, 11]
binarySearchTree.print(); // 看控制台


结果如下:


微信图片_20220513110458.png


看到这里,你能解答文章的题目 非线性表中的树、堆是干嘛用的 ?其数据结构是怎样的 ?


如果不能,建议再回头仔细看看哦。


3. 文章输出计划


JavaScript 数据结构与算法之美 的系列文章,坚持 3 - 7 天左右更新一篇,暂定计划如下表。


| 标题 | 链接 |

| :------ | :------ |

| 时间和空间复杂度 | https://github.com/biaochenxu... |

| 线性表(数组、链表、栈、队列) | https://github.com/biaochenxu... |

| 实现一个前端路由,如何实现浏览器的前进与后退 ?| https://github.com/biaochenxu... |

| 栈内存与堆内存 、浅拷贝与深拷贝 | https://github.com/biaochenxu... |

| 递归 | https://github.com/biaochenxu... |

| 非线性表(树、堆) | https://github.com/biaochenxu... |

| 冒泡排序 | 精彩待续 |

| 插入排序 | 精彩待续 |

| 选择排序 | 精彩待续 |

| 归并排序 | 精彩待续 |

| 快速排序 | 精彩待续 |

| 计数排序 | 精彩待续 |

| 基数排序 | 精彩待续 |

| 桶排序 | 精彩待续 |

| 希尔排序 | 精彩待续 |

| 堆排序 | 精彩待续 |

| 十大经典排序汇总 | 精彩待续 |

如果有错误或者不严谨的地方,请务必给予指正,十分感谢。


相关文章
|
2天前
|
存储 算法
【数据结构和算法】--- 二叉树(4)--二叉树链式结构的实现(2)
【数据结构和算法】--- 二叉树(4)--二叉树链式结构的实现(2)
7 0
|
2天前
|
算法 分布式数据库
【数据结构和算法】--- 二叉树(5)--二叉树OJ题
【数据结构和算法】--- 二叉树(5)--二叉树OJ题
8 1
|
1天前
|
算法 Java
Java数据结构与算法:最短路径算法
Java数据结构与算法:最短路径算法
|
2天前
|
存储 算法 搜索推荐
【数据结构和算法】--- 基于c语言排序算法的实现(2)
【数据结构和算法】--- 基于c语言排序算法的实现(2)
4 0
|
2天前
|
搜索推荐 算法 大数据
​【数据结构与算法】冒泡排序:简单易懂的排序算法解析
​【数据结构与算法】冒泡排序:简单易懂的排序算法解析
|
2天前
|
搜索推荐 算法 C语言
【数据结构和算法】--- 基于c语言排序算法的实现(1)
【数据结构和算法】--- 基于c语言排序算法的实现(1)
10 0
|
2天前
|
算法
【数据结构和算法】--- 二叉树(3)--二叉树链式结构的实现(1)
【数据结构和算法】--- 二叉树(3)--二叉树链式结构的实现(1)
4 0
|
2天前
|
算法 C语言
【数据结构与算法 经典例题】使用栈实现队列(图文详解)
【数据结构与算法 经典例题】使用栈实现队列(图文详解)
|
2天前
|
存储 测试技术
【数据结构】操作受限的线性表,栈的具体实现
【数据结构】操作受限的线性表,栈的具体实现
14 5