java implementation of simple binary tree

Posted by titangf on Fri, 01 Oct 2021 22:28:44 +0200

Basic knowledge of binary tree:

1, Definition of tree

Tree is a kind of data structure. It is a set with hierarchical relationship composed of n (n > = 1) finite nodes.

The tree has the following characteristics:

(1) Each node has zero or more child nodes

(2) A node without a parent node is called a root node

(3) Each non root node has only one parent node

(4) In addition to the root node, each child node can be divided into multiple disjoint subtrees.

The basic terms of the tree are:

If a node has a subtree, the node is called the "parent" of the subtree root, and the root of the subtree is called the "child" of the node. Nodes with the same parents are "brothers" to each other. Any node on all subtrees of a node is the descendant of that node. All nodes on the path from the root node to a node are the ancestors of that node.

Degree of node: the number of subtrees owned by a node

Leaf node: node with degree 0

Branch node: a node whose degree is not 0

Degree of tree: the maximum degree of a node in a tree

Level: the level of the root node is 1, and the level of other nodes is equal to the level of the parent node of the node plus 1

Height of tree: the maximum level of nodes in the tree

Forest: composed of 0 or more disjoint trees. Add a root to the forest, and the forest becomes a tree; Delete the root and the tree becomes a forest.

2, Binary tree

1. Definition of binary tree

A binary tree is a tree structure in which each node has at most two subtrees. It has five basic forms: binary tree can be an empty set; The root can have an empty left subtree or right subtree; Or the left and right subtrees are empty.

2. Properties of binary tree

Property 1: the maximum number of nodes on layer I of binary tree is 2i-1 (I > = 1)

Property 2: a binary tree with depth K has at most 2k-1 nodes (k > = 1)

Property 3: the height of a binary tree containing N nodes is at least (log2n)+1

Property 4: in any binary tree, if the number of terminal nodes is n0 and the number of nodes with degree 2 is n2, then n0=n2+1

3. Proof of property 4

Property 4: in any binary tree, if the number of terminal nodes is n0 and the number of nodes with degree 2 is n2, then n0=n2+1

It is proved that because the degrees of all nodes in the binary tree are not greater than 2, it is advisable to set n0 to represent the number of nodes with degree 0, n1 to represent the number of nodes with degree 1, and n2 to represent the number of nodes with degree 2. The sum of the three types of nodes is the number of summary points, so we can get: n=n0+n1+n2 (1)

The second equation can be obtained from the relationship between degrees: n=n00+n11+n2*2+1, that is, n=n1+2n2+1 (2)

If (1) and (2) are combined together, n0=n2+1 can be obtained

3, Full binary tree, complete binary tree and binary lookup tree

1. Full binary tree

Definition: a binary tree with a height of H and composed of 2h-1 nodes is called a full binary tree

2. Complete binary tree

Definition: in a binary tree, only the degree of the lowest two nodes can be less than 2, and the leaf nodes of the lowest layer are concentrated in several positions on the left. Such a binary tree is called a complete binary tree.

Features: leaf nodes can only appear in the lowest layer and sub lower layer, and the leaf nodes at the lowest layer are concentrated on the left of the tree. Obviously, a full binary tree must be a complete binary tree, and a complete binary tree may not be a full binary tree.

Interview question: if the total number of nodes of a complete binary tree is 768, find the number of leaf nodes.

From the properties of binary tree: n0=n2+1, bring it into 768=n0+n1+n2 to get: 768=n1+2n2+1, because the number of nodes with complete binary tree degree of 1 is either 0 or 1, then substitute n1=0 or 1 into the formula, and it is easy to find that n1=1 meets the condition. So n2=383, so the number of leaf nodes n0=n2+1=384.

Summary rule: if the total number of nodes of a complete binary tree is n, then the leaf nodes are equal to n/2 (when n is even) or (n+1)/2 (when n is odd)

3. Binary lookup tree

Definition: binary search tree is also called binary search tree. Let X be a node in the binary search tree, node x contains the keyword key, and the key value of node x is counted as key[x]. If y is a node in the left subtree of X, then key [y] < = key[x]; If y is a node of the right subtree of X, then key [y] > = key[x]

Find tree species in binary:

(1) If the left subtree of any node is not empty, the values of all nodes on the left subtree are less than those of its root node.

(2) If the right subtree of any node is not empty, the values of all nodes on the right subtree are greater than those of its root node.

(3) The left and right subtrees of any node are also binary search trees.

(4) There are no nodes with equal key values.

Requirements: store the number in an array in the storage structure of binary tree, and traverse and print.

import java.util.ArrayList;
import java.util.List;
public class bintree {
    public bintree left;
    public bintree right;
    public bintree root;
//    Data domain
    private Object data;
    //    Storage node
    public List<bintree> datas;
    public bintree(bintree left, bintree right, Object data){
//    Leave the initial left and right child values blank
    public bintree(Object data){
    public bintree() {
    public void creat(Object[] objs){
        datas=new ArrayList<bintree>();
        //        Convert the values of an array into Node nodes in turn
        for(Object o:objs){
            datas.add(new bintree(o));
//        The first number is the root node
//        Establish binary tree
        for (int i = 0; i <objs.length/2; i++) {
//            Left child
//            Right child
            if(i*2+2<datas.size()){//Avoid subscript out of bounds in even numbers
//Preorder traversal 
public void preorder(bintree root){
//Medium order traversal
    public void inorder(bintree root){
//    Postorder traversal
    public void afterorder(bintree root){
    public static void main(String[] args) {
        bintree bintree=new bintree();
        Object []a={2,4,5,7,1,6,12,32,51,22};

Requirements: input the number from the keyboard, save it as a binary tree structure and print it.

import java.util.Scanner;
public class btree {
    private btree left,right;
    private char data;
    public btree creat(String des){
        Scanner scanner=new Scanner(;
        if(str.charAt(0)<'a')return null;
        btree root=new btree();;
        root.left=creat(str.charAt(0)+"Left subtree");
        root.right=creat(str.charAt(0)+"Right subtree");
        return root;
    public void midprint(btree btree){
//        Medium order traversal
            System.out.print("  ");
    public void firprint(btree btree){
//        Preorder traversal 
            System.out.print(" ");
    public void lastprint(btree btree){
//        Postorder traversal
            System.out.print("  ");
    public static void main(String[] args) {
        btree tree = new btree();
        btree newtree=tree.creat("Root node");

Output results:

des: root node
des:a left subtree
des:e left subtree
des:c left subtree
des:c right subtree
des:e right subtree
des:b left subtree

des:b right subtree
des:a right subtree
des:d left subtree
des:f left subtree
des:f right subtree
des:d right subtree
a e c b d f precedence
c e b a f d middle order
c b e f d a post order

Traversal order of binary tree:

The first order is that the root node is ranked first, and then the same level is left first and then right; The middle order is first left, then root, and finally right; The last order is left first, then right, and finally the root.

For example:

For example, the binary tree traversal result in the figure above

Preorder traversal: ABCDEFGHK

Middle order traversal: BDCAEHGKF

Post order traversal: DCBHKGFEA

The traversal of the analysis middle order is shown in the figure below, and the middle order is more important (many java trees are sorted based on the middle order, which will be explained later)

Topics: Java Algorithm data structure