Binary tree and its traversal method + code

Posted by exoduses on Tue, 22 Feb 2022 12:27:22 +0100

1. Tree structure and basic concepts

1.1 tree structure concept

Tree is a nonlinear data structure. It is a set with hierarchical relationship composed of n (n > = 0) finite nodes. It is called a tree because it looks like an upside down tree, that is, it has its roots up and its leaves down.
Characteristics of tree structure

  1. Subtree disjoint
  2. Except for the root node, each node has one and only one parent node
  3. A tree with N nodes has N-1 edges

1.2 some important concepts

Degree of node: the number of subtrees contained in A node is called the degree of the node; As shown in the figure above: the degree of node A is 6
Tree degree: the degree of the largest node in a tree is called the degree of the tree; As shown in the figure above: the degree of the tree is 6
Leaf node or terminal node: a node with a degree of 0 is called a leaf node; As shown in the figure above: nodes B, C, H, I... Are leaf nodes
Parent node or parent node: if a node contains child nodes, this node is called the parent node of its child nodes; As shown in the figure above: A is the parent node of B
Child node or child node: the root node of the subtree contained in a node is called the child node of the node; As shown in the figure above: B is the child node of A
Root node: A node in A tree without parent nodes; As shown in the figure above: A
Hierarchy of nodes: defined from the root, the root is the first layer, and the child nodes of the root are the second layer, and so on;
Height or depth of tree: the maximum level of nodes in the tree; As shown in the figure above: the height of the tree is 4
Non terminal node or branch node: a node whose degree is not 0; As shown in the figure above, nodes D, E, F, G... Are branch nodes
Sibling node: nodes with the same parent node are called sibling nodes; As shown in the figure above: B and C are sibling nodes
Cousin node: nodes with parents on the same layer are cousins to each other; As shown in the figure above, H and I are brother nodes of each other
Ancestor of a node: all nodes from the root to the branch through which the node passes; As shown in the figure above: A is the ancestor of all nodes
Descendant: any node in the subtree with a node as the root is called the descendant of the node. As shown in the figure above: all nodes are descendants of A
Forest: a collection of m (m > = 0) disjoint trees is called forest

2. Binary tree and its basic concepts

2.1 binary tree concept

A binary tree is a finite set of nodes. The set is either empty or composed of a root node plus two binary trees called left subtree and right subtree.
Characteristics of binary tree:

1. Each node has at most two subtrees, that is, the binary tree does not have nodes with a degree greater than 2.
4. The subtree of a binary tree can be divided into left and right, and the order of its subtrees cannot be reversed. Therefore, a binary tree is an ordered tree.

2.2 two special binary trees

1. Full binary tree: a binary tree. If the number of nodes in each layer reaches the maximum, the binary tree is a full binary tree.
Conclusion:
5. If the number of layers of a full binary tree is K, the total number of nodes is 2^k - 1, and vice versa.
6. The number of nodes in layer K of full binary tree is 2^(k-1)
7. Side length of full binary tree = number of nodes - 1

2. Complete binary tree: complete binary tree is a highly efficient data structure. Complete binary tree is derived from full binary tree. A binary tree with depth K and n nodes is called a complete binary tree if and only if each node corresponds to the nodes numbered from 1 to n in the full binary tree with depth K. It should be noted that full binary tree is a special kind of complete binary tree.
Conclusion:
8. In a complete binary tree, if there is a node with degree 1, there is only one, and there is only a left subtree and no right subtree
9. The node numbers of complete binary tree and full binary tree correspond one by one

2.3 properties of binary tree

  1. If the specified number of layers of the root node is 1, there are at most 2 ^ (k-1) (k > 0) nodes on the k-th layer of a non empty binary tree, which is full of binary trees.
  2. If the depth of the binary tree with only the root node is specified as 1, the maximum number of nodes of the binary tree with depth K is 2 ^ k - 1 (k > = 0)
  3. For any binary tree, if the number of leaf nodes is n0 and the number of non leaf nodes with degree 2 is n2, then n0 = n2 + 1
  4. The depth k of a complete binary tree with n nodes is rounded on log2(n+1)
  5. The root node is numbered from 1. If the parent node number is k, the left subtree 2k and the right subtree 2k+1
    The root node is numbered from 0. If the parent node number is k, the left subtree 2k+1 and the right subtree 2k+2
    If the child node number is k, the parent node number is k/2

2.4 storage of binary tree

The storage structure of binary tree is divided into sequential storage and chain storage similar to linked list
The chained storage of binary tree is referenced by nodes one by one. The common representations include binary and trigeminal representations, as follows:

// Child representation
class Node {
 int val; // Data domain
 Node left; // The reference of the left child often represents the whole left subtree with the left child as the root
 Node right; // The reference of the right child often represents the whole right subtree with the right child as the root
}
// Child parent representation
class Node {
 int val; // Data domain
 Node left; // The reference of the left child often represents the whole left subtree with the left child as the root
 Node right; // The reference of the right child often represents the whole right subtree with the right child as the root
 Node parent; // The root node of the current node
}

2.5 basic operation of binary tree

2.5.1 traversal of binary tree

1. Preorder traversal: access the root node - > recursively access the left subtree of the root - > recursively access the right subtree of the root. (left and right)
2. Pre order traversal: left subtree of root - > root node - > right subtree of root. (left and right)
3. Pre order traversal: left subtree of root - > right subtree of root - > root node. (left and right)

Preorder traversal result: ABDEHCFG
Preorder features: in the preorder traversal result set, the first output must be the root node of the current tree
Middle order traversal result: DBEHAFCG
Middle order features: in the middle order traversal results, the traversal results of the left subtree are on the left side of the root node, and the traversal results of the right subtree are on the right side of the root
Post order traversal result: DHEBFGCA
Post order feature: in the post order traversal result, the last output root node
Note:

  1. A binary tree can be restored according to the traversal results of preorder and inorder
  2. Compare the backward traversal result with the previous traversal result:
    Post order traversal transpose: ACGFBEHD
    Preorder traversal: ABDEHCFG
    The subsequent transpose happens to be the mirror image of the preorder traversal: the root is right and left

2.5.2 code

Create binary tree code above

package bin_tree;
/**
 * Implementation of basic binary tree
 * Left and right child representation
 */
public class MyBinTree {
    private static class TreeNodes{
        char val; // Node value
        TreeNodes left; // Left subtree root node
        TreeNodes right;  // Right subtree root node
        // Construction method
        public TreeNodes(char val) {
            this.val = val;
        }
    }
    /**
     * Create a binary tree and return the root node
     */
    public static TreeNodes build(){
        // Create 8 nodes
        TreeNodes nodeA=new TreeNodes('A');
        TreeNodes nodeB=new TreeNodes('B');
        TreeNodes nodeC=new TreeNodes('C');
        TreeNodes nodeD=new TreeNodes('D');
        TreeNodes nodeE=new TreeNodes('E');
        TreeNodes nodeF=new TreeNodes('F');
        TreeNodes nodeG=new TreeNodes('G');
        TreeNodes nodeH=new TreeNodes('H');
        // Connect the eight nodes
        nodeA.left=nodeB;
        nodeA.right=nodeC;
        nodeB.left=nodeD;
        nodeB.right=nodeE;
        nodeE.right=nodeH;
        nodeC.left=nodeF;
        nodeC.right=nodeG;
        return nodeA;

    }
}

Preorder traversal code (about root)

/**
     * Traversing a binary tree in advance, passing in the root node of a binary tree, you can traverse the node in the way of traversing in advance
     * Root left and right
     * @param root
     */
 public static void preOrder(TreeNodes root){
        // Air judgment
        if(root==null){
            return;
        }
        // Output root node
        System.out.println(root.val + " ");
        // Recursive left subtree
        preOrder(root.left);
        // Recursive right subtree
        preOrder(root.right);
    }

Middle order traversal: left root right

 /**
     * Traversing a binary tree in middle order, passing in the root node of a binary tree, you can traverse the node in the way of middle order traversal
     * Zuo Genyou
     * @param root
     */
    public static void inOderTraversal(TreeNodes root){
        // Air judgment
        if(root==null){
            return;
        }
        // Recursive left subtree
        inOderTraversal(root.left);
        // Output root node
        System.out.println(root.val + " ");
        // Recursive right subtree
        inOderTraversal(root.right);
    }

Post order traversal: left and right roots
If you pass in the root node of a binary tree, you can traverse the nodes in the middle order

 /**
     * Post order traversal: left and right roots
     * If you pass in the root node of a binary tree, you can traverse the nodes in the middle order
     */
    public static void postOderTraversal(TreeNodes root){
        // Air judgment
        if(root==null){
            return;
        }
        // Recursive left subtree
        postOderTraversal(root.left);
        // Recursive right subtree
        postOderTraversal(root.right);
        // Output root node
        System.out.println(root.val + " ");
    }

Complete code + test

package bin_tree;
/**
 * Implementation of basic binary tree
 * Left and right child representation
 */
public class MyBinTree {
    private static class TreeNodes{
        char val; // Node value
        TreeNodes left; // Left subtree root node
        TreeNodes right;  // Right subtree root node
        // Construction method
        public TreeNodes(char val) {
            this.val = val;
        }
    }
    /**
     * Create a binary tree and return the root node
     */
    public static TreeNodes build(){
        // Create 8 nodes
        TreeNodes nodeA=new TreeNodes('A');
        TreeNodes nodeB=new TreeNodes('B');
        TreeNodes nodeC=new TreeNodes('C');
        TreeNodes nodeD=new TreeNodes('D');
        TreeNodes nodeE=new TreeNodes('E');
        TreeNodes nodeF=new TreeNodes('F');
        TreeNodes nodeG=new TreeNodes('G');
        TreeNodes nodeH=new TreeNodes('H');
        // Connect the eight nodes
        nodeA.left=nodeB;
        nodeA.right=nodeC;
        nodeB.left=nodeD;
        nodeB.right=nodeE;
        nodeE.right=nodeH;
        nodeC.left=nodeF;
        nodeC.right=nodeG;
        return nodeA;

    }
    /**
     * Traversing a binary tree in advance, passing in the root node of a binary tree, you can traverse the node in the way of traversing in advance
     * Root left and right
     * @param root
     */
    public static void preOrder(TreeNodes root){
        // Air judgment
        if(root==null){
            return;
        }
        // Output root node
        System.out.print(root.val + " ");
        // Recursive left subtree
        preOrder(root.left);
        // Recursive right subtree
        preOrder(root.right);
    }
    /**
     * Traversing a binary tree in middle order, passing in the root node of a binary tree, you can traverse the node in the way of middle order traversal
     * Zuo Genyou
     * @param root
     */
    public static void inOderTraversal(TreeNodes root){
        // Air judgment
        if(root==null){
            return;
        }
        // Recursive left subtree
        inOderTraversal(root.left);
        // Output root node
        System.out.print(root.val + " ");
        // Recursive right subtree
        inOderTraversal(root.right);
    }
    /**
     * Post order traversal: left and right roots
     * If you pass in the root node of a binary tree, you can traverse the nodes in the middle order
     */
    public static void postOderTraversal(TreeNodes root){
        // Air judgment
        if(root==null){
            return;
        }
        // Recursive left subtree
        postOderTraversal(root.left);
        // Recursive right subtree
        postOderTraversal(root.right);
        // Output root node
        System.out.print(root.val + " ");
    }
    public static void main(String[] args) {
        TreeNodes root=build();
        System.out.print("The preorder traversal result is:");
        preOrder(root);
        System.out.println();
        System.out.print("The middle order traversal result is:");
        inOderTraversal(root);
        System.out.println();
        System.out.print("The post order traversal result is:");
        postOderTraversal(root);
    }
}

Topics: data structure