JS articles --- binary tree data structure fifth and binary search tree

First, the basic concept of a binary tree

From the perspective of the logical structure, said earlier linked lists, stacks, queues are linear structure; today to understand the "binary" is a tree structure.

The basic concept of over 1.1-tree, above the figure "multi-tree" as an example

  Node : Each point called multi-branch tree node ; most of the top node called " root ";

  Parent : 2/3/4/5/6 node 1 is a node of the parent node , then the node is a node 1 2/3/4/5/6 child node ; node is 2/3/4/5/6 each other sibling , because they have the same parent as a node;

  Empty tree : a tree called node does not have any empty tree ; a tree can have only one node, that is, only the root node;

  Sub-tree : a collection of nodes and sub-nodes backstage child node form is called sub-tree; for the node has only two child nodes, child nodes to its left called the left subtree, right subtree called the right;

  Leaf node (Leaf) : sub-tree node 0; other sub-tree is not called "nodes 0 of non-leaf nodes ";

  Layers (Level) : the root node in the second layer, and so on (some claims also begin clearing from Layer 0) in the first layer, the sub-root node;

  Depth of the node (depth) : the total number of nodes on the unique path from the root to the current node;

  Node height (height) : total number of nodes on the farthest from the current node to the leaf node of the path;

  The depth of the tree : the maximum depth of all the nodes;

  Height of the tree : it is the maximum height of the node; number of depth equal to the height of the number of

  Ordered tree : sequential relationship between the child node to any node in the tree;

  Unordered tree : there is no relationship between the order, also known as "Freedom Tree" between sub-tree node to any node;

  Forest : a n (n> = 0) set of disjoint trees pieces thereof;

1.2 Binary Tree Features

  • The maximum degree of each node is 2 (two subtree with the most);
  • Left subtree and right subtree is in order. Even if a tree node has only one child, but also to distinguish between left and right sub-tree;
  • I-th layer of non-null binary tree, up to 2 ^ (i-1) th node (i> = 1)
  • In the binary tree height h up to 2 ^ h - 1 nodes (h> = 1);
  • A binary tree for any non-empty, if the number of leaf nodes n0, the number of nodes of degree 2 is n2, there is n0 = n2 + 1. (This is easy to understand, in addition to a first stage if the binary tree node has two child nodes, the node is behind only one child node, regardless of how the binary tree Zheke extending downward, is always the number of nodes is 2 1, 2 is a leaf node; if then this intermediate node binary tree, each adding a node corresponding to a node of degree 2 is a plus, plus also a leaf node, the node degree increases and the leaf nodes are synchronized with the 2 number, so the binary tree, the number of leaf nodes is the node number = 1 + equation 2 is always established)
  • 1 is the number of nodes assumed as n1, then the total number of nodes in the binary tree n = n0 + n1 + n2. The number of edges of binary tree T = n1 + 2 * n2 = n -1 = n0 + n1 + n2 -1 -> n2 + 1 = n0

1.3 true binary / binary full / complete binary tree

  • True binary: either all of the nodes are 2 or 0;
  • Full binary tree: all of the nodes are either 2 or 0, and all of the leaf nodes are the final layer;
    • Assuming full binary tree height (h> = 1) h, then the number of nodes in layer i: 2 ^ (i-1), the number of leaf nodes: 2 (^ h-1), the total number of nodes n = 2 ^ h -1 = 2 ^ 0 + 2 ^ 1 + 2 ^ 2 + ... + 2 ^ (h-1)
    • Geometric series formula: a1 = 1, the common ratio q = 2, then an = a1 * q ^ (n-1) = 2 ^ (n-1), a sum of the first n Sn = a1 + a2 + ... + an = 2 ^ 0 + 2 ^ 1 + 2 ^ 2 + ... + 2 ^ (n-1) = a1 (1-q ^ n) / (1-q) = 2 ^ n-1
    • At the same height of a binary tree, the largest number of full binary tree leaf nodes, up to the total number of nodes;
    • Full binary tree binary tree must be really, really is not necessarily a binary tree is a full binary tree;
  • Complete binary tree: the leaf node will only appear in the last two, and the last layer of leaf nodes are aligned to the left;
    • Complete binary tree from the root to the penultimate layer is a full binary tree; full binary must be complete binary tree, not necessarily a complete binary tree is a full binary tree;
    • A node of degree 1 only the left subtree; degree of a node is either a 1 or a 0;
    • Assuming complete binary tree of a height (h> = 1) h, then at least 2 ^ (h-1) th node (2 ^ 0 + 2 ^ 1 + 2 ^ 2 + ... + 2 ^ (h-2) + 1), up to 2 ^ h - 1 nodes (2 ^ 0 + 2 ^ 1 + 2 ^ 2 + ... + 2 ^ (h-1), a full binary tree); the total number of nodes is n, then there are 2 ^ (h-1) <= n <2 ^ h -> h-1 <= log (2) (n) <h -> h = floor (log (2) (n)) + 1 (floor is rounded down, ceiling is rounded up)
    • A complete binary tree has n nodes (n> 0), from top to bottom, left to right nodes numbered from 1, for any node i
      • If i = 1, it is the root node
      • If i> 1, its parent numbered floor (i / 2)
      • If 2i <= n, its left child node number 2i
      • If 2i> n, it has no left child
      • If 2i + 1 <= n, which is the right child node number 2i + 1
      • If 2i + 1> n, it has no right child node  

   

Interview questions: If a complete binary tree has 768 nodes, find the number of leaf nodes?

Analysis: Suppose the number of leaf nodes n0, 1 degree is the number of node n1, the node number of degree 2 is n2.

  The total number of nodes n = n0 + n1 + n2, and n0 = n2 + 1;

  Then n = 2n0 + n1 -1

  According to the definition of complete binary tree we know, n1 is either 0 or 1:

  When n1 is 1, n = 2n0, n is necessarily an even number. The number of leaf nodes n0 = n / 2, the number of non-leaf nodes n1 + n2 = n / 2;

  When n1 is 0, n = 2n0 - 1, n is necessarily an odd number. The number of leaf nodes n0 = (n + 1) / 2, the number of non-leaf nodes n1 + n2 = (n1) / 2

  It can be judged when the complete binary tree has a node 768, which is the number of leaf nodes: 384

 

Second, the binary search tree

Binary search tree is a special kind of binary tree, the smaller value is stored in the left node, the larger value is stored in the right node. This feature makes finding a high efficiency, for numeric and non-numeric data, such as words and strings, it is true.

2.1 binary search tree insertion logic

  2.1.1 set the root to the current node

  2.1.2 If the saved node data to be inserted is smaller than the current node, the new current node located to the left of the node of the primary node; otherwise, go to step 2.1.4

  2.1.3 If the left of the current node is null, it will be a new node into this position, exit the loop; on the contrary, continue to the next time through the loop

  2.1.4 set the new current node is the right node of the original node

  2.1.5 If the right of the current node is null, a new node will be inserted into this position, the loop is exited; otherwise, execution continues with the next cycle

//插入元素
    function insertBST(element){
        var node = new Node(element, null, null);

        //根节点判断
        if (root == null){
            root = node;
        }
        else{ //非根节点
            var current = root;
            while(true){
                if (element < current.element){ //往左节点方向放
                    if (current.left == null){
                        current.left = node;
                        break;
                    }
                    current = current.left;
                }
                else if (element > current.element){ //往右节点方向放
                    if (current.right == null){
                        current.right = node;
                        break;
                    }
                    current = current.right;
                }
                else { //相等,替换
                    current.element = element;
                    return;
                }
            }
        }
        size++;
    }
View Code

2.2 二叉查找树的遍历,遍历有三种方式:中序、前序、后序

  中序指以升序的方式遍历所有节点;前序是指先访问根节点,再以同样的方式访问左子树和右子树;后序指的是先访问叶子节点,再从左子树到右子树,最后到根节点。

先看个效果图

遍历走势分析图:

遍历代码:

//二叉树中序遍历:以升序方式访问二叉树中所有节点
    function inOrder(){
        return inOrderByNode(root);
    }
    function inOrderByNode(node){
        if (node){
            var str = "";
            str += inOrderByNode(node.left);
            str += node.element + ", ";
            str += inOrderByNode(node.right);
            return str;
        }
        return "";
    }


    //前序遍历:先访问根节点,再访问左子树和右子树
    function preOrder(){
        return preOrderByNode(root);
    }
    function preOrderByNode(node){
        if (node){
            var str = '';
            str += node.element + ", "; //先访问根节点
            str += preOrderByNode(node.left); //再访问左子树
            str += preOrderByNode(node.right); //再访问右子树
            return str;
        }
        return "";
    }


    //后序遍历:先访问叶子节点,再左子树,再右子树,再到根节点
    function postOrder(){
        return postOrderByNode(root);
    }
    function postOrderByNode(node){
        if (node){
            var str = "";
            str += postOrderByNode(node.left);
            str += postOrderByNode(node.right);
            str += node.element + ", ";
            return str;
        }
        return "";
    }
View Code

 

2.3 查找二叉查找树的最大值、最小值、是否存在某个值

最大值:因为较大的值都是在右子树上,则最大值一定是在右子树的最后一个节点上;

最小值:较小的值都是在左子树上,则最小值一定在左子树的最后一个节点上;

是否存在某个值,则是遍历查找

//查找最小值:因为较小的值都在左边,所以最小值一定是左子树的最后一个节点
    function getMin(){
        var minNode = getMinNode(root);
        if (minNode) {
            return minNode.element;
        }
        return null;
    }
    //查找最小节点
    function getMinNode(node){
        var current = node;
        while(current){
            if (current.left == null){
                return current;
            }
            current = current.left;
        }
        return null;
    }

    //查找最大值:因为较大的值都在右边,所以最大值一定是在右子树的最后一个节点
    function getMax(){
        var maxNode = getMaxNode(root);
        if (maxNode){
            return maxNode.element;
        }
        return null;
    }
    //查找最大节点
    function getMaxNode(node){
        var current = node;
        while(current){
            if (current.right == null){
                return current;
            }
            current = current.right;
        }
        return null;
    }

    //查找指定值,是否存在这个元素
    function isExist(element){
        var current = root;
        while(current){
            if (element < current.element){ //左子树寻找
                current = current.left;
            }
            else if (element > current.element){ //右子树寻找
                current = current.right;
            }
            else{ //存在
                return true;
            }
        }
        return false;
    }
View Code

 

2.4 删除二叉查找树中的指定元素

从二叉查找树上删除节点的操作最复杂,其复杂程度取决于删除哪个节点。如果删除没有子节点 的节点,那么非常简单。如果节点只有一个子节点,不管是左子节点还是右子节点,就变 得稍微有点复杂了。删除包含两个子节点的节点最复杂。

//删除元素
    function remove(element){
        root = removeNode(root, element);
    }
    function removeNode(node, element){
        if (node == null) {
            return null;
        }

        if (node.element == element){
            size--;
            //node没有左子树
            if (node.left == null){
                return node.right;
            }
            else if (node.right == null){ //node没有右子树
                return node.left;
            }
            /**
             * node有左子树和右子树,这个时候要找出最接近node节点值的节点
             * 1、如果找出比node节点的element稍大的节点,则从node右节点的最小节点
             * 2、如果找出比node节点的element稍小的节点,则从node左节点的最大节点
             */
            //第一种方式,找出比node的element稍微大点的节点
            var minNode = getMinNode(node.right);
            node.element = minNode.element;
            node.right = removeNode(node.right, minNode.element);

            // //第二种方式, 找出比node的element稍微小点的节点
            // var maxNode = getMaxNode(node.left);
            // node.element = maxNode.element;
            // node.left = removeNode(node.left, maxNode.element);

            return node;
        }
        else if(element < node.element){ //往左子树方向继续找
            node.left = removeNode(node.left, element);
            return node;
        }
        else{
            //往右子树方向继续找
            node.right = removeNode(node.right, element);
            return node;
        }
    }
View Code

 

完整demo见:https://github.com/xiaotanit/Tan_DataStruct

Guess you like

Origin www.cnblogs.com/tandaxia/p/11234454.html