# 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){
this.left=left;
this.right=right;
this.data=data;
}
//    Leave the initial left and right child values blank
public bintree(Object data){
this(null,null,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){
}
//        The first number is the root node
root=datas.get(0);
//        Establish binary tree
for (int i = 0; i <objs.length/2; i++) {
//            Left child
datas.get(i).left=datas.get(i*2+1);
//            Right child
if(i*2+2<datas.size()){//Avoid subscript out of bounds in even numbers
datas.get(i).right=datas.get(i*2+2);
}
}
}
//Preorder traversal
public void preorder(bintree root){
if(root!=null){
System.out.println(root.data);
preorder(root.left);
preorder(root.right);
}
}
//Medium order traversal
public void inorder(bintree root){
if(root!=null){
inorder(root.left);
System.out.println(root.data);
inorder(root.right);
}
}
//    Postorder traversal
public void afterorder(bintree root){
if(root!=null){
System.out.println(root.data);
afterorder(root.left);
afterorder(root.right);
}
}
public static void main(String[] args) {
bintree bintree=new bintree();
Object []a={2,4,5,7,1,6,12,32,51,22};
bintree.creat(a);
bintree.preorder(bintree.root);
}
}

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(System.in);
System.out.println("des:"+des);
String str=scanner.next();
if(str.charAt(0)<'a')return null;
btree root=new btree();
root.data=str.charAt(0);
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
if(btree!=null){
midprint(btree.left);
System.out.print(btree.data+"  ");
midprint(btree.right);
}
}
public void firprint(btree btree){
//        Preorder traversal
if(btree!=null){
System.out.print(btree.data+" ");
firprint(btree.left);
firprint(btree.right);
}
}
public void lastprint(btree btree){
//        Postorder traversal
if(btree!=null){
lastprint(btree.left);
lastprint(btree.right);
System.out.print(btree.data+"  ");
}
}
public static void main(String[] args) {
btree tree = new btree();
btree newtree=tree.creat("Root node");
tree.firprint(newtree);
System.out.println();
tree.midprint(newtree);
System.out.println();
tree.lastprint(newtree);
}
}

Output results:

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

1
des:b right subtree
1
des:a right subtree
d
des:d left subtree
f
des:f left subtree
1
des:f right subtree
1
des:d right subtree
1
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