SilenceHVK / blog

:books: :octocat: Github static blog post, experience the fun of using Issues.Welcome star( 静态博客文章,体验一下使用 Issues 的乐趣,欢迎 star )个人博客地址:blog.hvkcoder.me/love
https://github.com/SilenceHVK/Articles/issues
MIT License
231 stars 9 forks source link

【算法详解】二叉树(Binary Tree) #57

Open SilenceHVK opened 5 years ago

SilenceHVK commented 5 years ago

什么是二叉树

  二叉树是一种具有层级特性的数据结构,它是由一系列节点组成,其每个节点最多只能有两个子节点。 如图所示:

Binary Tree

二叉排序树

  二叉排序树,又称为二叉查找树二叉搜索树。其特点为,左子树上所有的节点值均小于它的根节点值,右子树上所有的节点值均大于它的根节点值。且没有相等的节点值 如图所示:

Binary Sort Tree

二叉排序树的创建

'use strict'

class Node {
    constructor(key) {
        this.key = key;
        this.left = null;
        this.right = null;
    }

    insertNode(newNode) {
        /**
         * 二叉排序树的定义:
         * 左子树上所有子节点均小于其根节点,
         * 右子树上所有的子节点均大于其根节点
         */
        if (this.key > newNode.key) {
            if (this.left === null) {
                this.left = newNode;
            } else {
                this.left.insertNode(newNode);
            }
        } else {
            if (this.right === null) {
                this.right = newNode;
            } else {
                this.right.insertNode(newNode);
            }
        }
    }
}

function BinarySortTree(nodes) {
    let root = null;
    if (nodes && nodes.length > 0) {
        nodes.forEach(item => {
            const newNode = new Node(item);
            if (root === null) {
                root = newNode;
            } else {
                root.insertNode(newNode);
            }
        });
    }
    return root;
}