java implementation-data structure of the binary tree (two): sequential storage of the binary tree

Data structure of the binary tree (two): sequential storage of the binary tree

Concept:
From the perspective of data storage, sequential storage of binary trees means that the array storage method and the tree storage method can be mutually converted, that is, the array can be converted into a tree, and the tree can also be converted into an array.
For example, the following figure:
Insert picture description here
(Sequential binary trees usually only consider complete binary trees)
From the above figure, we can see that the array subscript corresponds to the number of the tree node.
The node number of the left subtree of the nth node of the binary tree is 2 n+1;
the node number of the right subtree

of the nth node of the binary tree is 2 n+2;the node number of the parent node of the nth node of the binary tree Is (n-1)/2;

A simple implementation of converting an array to a binary tree:

public class ArrayBinaryTreeDemo {
    
    
	public static void main(String[] args) {
    
    
		int arr[]= {
    
    1,2,3,4,5,6,7};
		ArrayBinaryTree abTree=new ArrayBinaryTree(arr);
		abTree.preShow(0);
	}
}

class ArrayBinaryTree{
    
    
	int arr[];
	public ArrayBinaryTree(int arr[]) {
    
    
		this.arr=arr;
	}
	
	//将数组转换为树后的前序遍历,index为数组下标
	public void preShow(int index) {
    
    
		if(arr==null||arr.length==0) {
    
    
			System.out.println("数组为空,转换树失败");
		}
		System.out.println(arr[index]);
		if((2*index+1)<arr.length) {
    
    
			preShow(2*index+1);
		}
		if((2*index+2)<arr.length) {
    
    
			preShow(2*index+2);
		}
	}
}

The output of the preorder traversal result:
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_45273552/article/details/109080102