java array data structure to achieve: freedom tree

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/Mr__Viking/article/details/89487561

Before we study the structure of the data type linear arrays and linked lists, look at today nonlinear structure data type of tree ( one to many ). Tree often used in our daily lives, such as our paper catalog, department staff structure diagram of a computer system and file structure, and so on. It is more as compared to a general linear structure having a hierarchy, it is more powerful than a linear function of the data structure. Therefore, the author of this article explain how to use the array to achieve a free tree.

Start online collection at the relevant definitions and attributes the characteristics of the tree:

Explanation

FIG tree is a data structure which is n (n> = 1) consisting of a finite nodes having a hierarchical relationship set . We call it the "tree" because it looks like an upside down tree, which means that it is the root upward, downward and leaves. It has the following features:

Each node has zero or more child nodes; no parent node is called the root node; each non-root node has only one parent node; root addition, each child node It can be divided into multiple sub-tree disjoint

definition

Tree (Tree) comprising n (n> = 0) is a finite set of nodes, wherein:

(1) Each element node is called (Node);

(2) a specific node is called the root node or the root (root).

(3) the remaining data elements other than the root node is divided into m (m≥0) disjoint set T1, T2, ...... Tm-1, wherein each set Ti (1 <= i <= m ) itself is a tree, the tree is referred to the original subtree (subtree).

The tree can be defined: the root and the tree is a subtree composed of several pieces. Tree is constituted by a set and a relationship defined in the set. Elements of the collection called tree nodes, parent-child relationship definition is called relationship. Parent-child relationship between the nodes of the tree establishes a hierarchy. There is a node having a special position in this hierarchy, this node is called the root node of the tree, otherwise known as root.

We can give form to a tree recursively defined as follows:

Single node is a tree, which is the root node itself.

Set T1, T2, .., Tk is a tree, the root of which are n1, n2, .., nk. With n as a new node n1, n2, .., nk father, a new tree is obtained, n is the new root node of the tree. We call n1, n2, .., nk is a set of sibling nodes, which are nodes of a child node n. We also said T1, T2, .., Tk is the subtree node n.

Empty set is the tree, called the empty tree. No empty tree nodes.

Related Terms

Of the node : a node number subtree containing of the node is referred to;

Terminal node or leaf node : a node of degree 0 is called a leaf node;

A non-terminal node or a branch node : node degree is not 0;

Parent or parent node : If a node comprising a child node, this node is called a parent node to its child nodes;

Child or children : the root node of a subtree containing the called child nodes of the node;

Sibling nodes : nodes having the same parent node is called mutual sibling nodes;

Of the tree : a tree, the maximum degree of the tree is called a node;

Level node : from the definition of the start from the root, the root of the first layer, children of the root of the second layer, and so on;

Tree height or depth : The maximum level nodes in the tree;

Cousins node : parent node in the same layer of each other cousins;

Ancestor node : All nodes on branches from the root through to the node;

Sons : a node in the subtree rooted at a node referred to in any of the descendant node.

Forest : a set of m (m> = 0) disjoint trees called forest trees;

After reading a lot of the above terminology introduced since, in your mind you should have a general model, but it may not be enough clear, let's use a map to help us understand it.

                                                                A schematic view of the tree structure

This picture says a free form of a tree, if we put this picture rotated 180 °, so that each structure will be close like we live in a tree at the bottom of the tree is the root of the tree and trunk, then there is no cross-up is the relationship between the trunk of the tree to grow the tree branches, branches are independent from the trunk out part, then further on is the leaves of the tree.

Today, we learn that the tree can also use these terms to describe, but we learn of this tree is upside down, it is the top of its roots (Figure No. 1 is the root node), a tree structure can have at most one root (which can no root, the root of a tree is not empty tree we call), there may be below the root node 0-n (2,3,4 are in the root node of the sub- node), and below each node can have child nodes 0-n ... no child node we call leaves (5,6,7,8 belong to the leaf node), because it is already a top level. Further except the root, leaf, or the remaining nodes of the tree structure has one and only one parent node.

Each node in the tree structure to have only one unique path between the root node.

You need to specify who its parent is adding a new node to the tree structure: adding a new node operation.

                              

                                                                            Add a new node schematic

FIG Red No. 9 as the newly added node, which specifies the parent node is 2, so even after addition of a node in the node 9, No. 2 below.

Delete node operation: If you delete a node is a leaf node, only to remove it themselves, otherwise it will remove the node and all its descendant nodes, if a node is the root node delete, delete the entire tree.

                                       

                                                                                     Schematic delete nodes

FIG 3 is deleted node, the node and its children No. 3 No. 6 and 7 are deleted.

Traversal operation: the road map to find out all of the nodes to the root and find all of the nodes.

                                              

                                                                                     Node traversal schematic

achieve

After the theoretical study of the relevant characteristics of the tree structure we now use code to implement it.

There are two ways to achieve the tree:

  1. Array
  2. List

Today, this article will describe how to use the array to achieve freedom tree.

First sort out the demand:

  1. We need to create a tree
  2. Can be implemented to add new nodes to a tree
  3. Can be achieved delete a node and its children in the tree
  4. You can return depth of the tree
  5. You can traverse all nodes in the tree
  6. You can return a node's parent
  7. A node can return all the child nodes below

Temporarily we will first finish the seven requirements;

Man of few words said on the code:

package dataStructure;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Viking on 2019/4/22
 */
public class MyArrayTree<E> {

    private static final int DEFAULT_SIZE=20;
    private int size;
    private Node<E>[] nodes;
    private int nodeNum;

    @SuppressWarnings("unchecked")
    public MyArrayTree(E data){
        size = DEFAULT_SIZE;
        nodes = new Node[size];
        nodes[0] = new Node<>(data,-1);
        nodeNum++;
    }
    @SuppressWarnings("unchecked")
    public MyArrayTree(E data,int capacity){
        size = capacity;
        nodes = new Node[size];
        nodes[0] = new Node<>(data,-1);
        nodeNum++;
    }

    /**
     * 添加新节点
     */
    public Node<E> addNode(E data,Node parent){
        for (int i=0;i<size;i++){
            if (null==nodes[i]) {
                nodes[i] = new Node<>(data, pos(parent));
                nodeNum++;
                return nodes[i];
            }
        }
        throw new RuntimeException("该树已满,无法添加新节点");
    }

    /**
     * 删除节点及其所有子节点
     */
    public void remove(Node node){
        while (children(node).size()>0){
            for (Node child : children(node)){
                remove(child);
            }
        }
        for (int i=0;i<nodes.length;i++){
            if (nodes[i]!=null&&nodes[i]==node){
                nodes[i]=null;
                size--;
            }
        }
    }
    public List<String> list(){
        return list(getRoot());
    }
    public List<String> list(Node root){
        return list(new ArrayList<>(),"",root);
    }
    /**
     * 遍历
     */
    private List<String> list(List<String>list,String index,Node root){
        List<Node<E>> children = children(root);
        list.add(index+root.data);
        while (children.size()>0){
            for (Node node : children){
                list = list(list,index+"\t",node);
            }
            children.clear();
        }
        return list;
    }

    public boolean isEmpty(){
        return nodeNum==0;
    }
    public Node<E> getRoot(){
        return nodes[0];
    }
    public Node<E> getParent(Node node){
        return nodes[node.parent];
    }
    /**
     * 列出所有的子节点
     */
    public List<Node<E>> children(Node node){
        List<Node<E>> list = new ArrayList<>();
        for (int i=0;i<size;i++){
            if (null!=nodes[i]&&nodes[i].parent==pos(node))
                list.add(nodes[i]);
        }
        return list;
    }

    /**
     * 树的深度
     */
    public int deep(){
        int max = 0;
        for (int i = 0;i<size&&nodes[i]!=null;i++){
            int deep = 1;
            int p = nodes[i].parent;
            while(-1!=p&&nodes[p]!=null){
                p = nodes[p].parent;
                deep++;
            }
            if (deep>max) max = deep;
        }
        return max;
    }

    private int pos(Node node){
        for (int i=0;i<size;i++){
            if (nodes[i]==node) return i;
        }
        return -1;
    }

    public static class Node<T>{
        T data;
        int parent;

        public Node(T data ,int parent){
            this.data = data;
            this.parent = parent;
        }
    }
}

Write a test class: 

import dataStructure.MyArrayTree;

import java.util.List;

/**
 * Created by Viking on 2019/4/22
 * 测试自定义实现的树形结构
 */
public class TestMyTree {

    public static void main(String[] args) {
        MyArrayTree<String> tree = new MyArrayTree<>("root");
        System.out.println("Before add node:"+tree.deep());
        MyArrayTree.Node<String> node = tree.addNode("node", tree.getRoot());
        System.out.println("After add node:"+tree.deep());
        MyArrayTree.Node<String> root = tree.getRoot();
        List<MyArrayTree.Node<String>> children = tree.children(root);
        tree.addNode("Children",children.get(0));
        System.out.println("After children node:"+tree.deep());
        tree.remove(tree.children(children.get(0)).get(0));
        System.out.println("After remove node:"+tree.deep());
        MyArrayTree.Node<String> left = tree.addNode("left", root);
        MyArrayTree.Node<String> right = tree.addNode("right", root);
        tree.addNode("grandson1OfLeft",left);
        tree.addNode("grandson2OfLeft",left);
        tree.addNode("grandson1OfRight",right);
        tree.addNode("grandson2OfRight",right);
        MyArrayTree.Node<String> childOfNode = tree.addNode("childOfNode", node);
        tree.addNode("childOfNodes'child",childOfNode);
        List<String> list = tree.list();
        for (String data : list){
            System.out.println(data);
        }
        System.out.println("----------------------------------");
        List<String> list1 = tree.list(node);
        for (String data : list1){
            System.out.println(data);
        }
    }
}

Test Results:

Before add node:1
After add node:2
After children node:3
After remove node:2
root
	node
		childOfNode
			childOfNodes'child
	left
		grandson1OfLeft
		grandson2OfLeft
	right
		grandson1OfRight
		grandson2OfRight
----------------------------------
node
	childOfNode
		childOfNodes'child

 

Guess you like

Origin blog.csdn.net/Mr__Viking/article/details/89487561