顺序存储的二叉树的遍历

package 顺序存储二叉树的遍历;

import java.lang.reflect.Array;

public class ArrayBinaryTree {
        public static void main(String[] args) {
            int data[]=new int[]{1,2,3,4,5,6,7};
            ArrayBinaryTree abt=new ArrayBinaryTree(data);
            System.out.println("顺序存储的前序遍历:");
            abt.frontShow();
            System.out.println();
            System.out.println("顺序存储的中序遍历:");
            abt.midShow();
            System.out.println();
            System.out.println("顺序存储的后序遍历:");
            abt.afterShow();
        
            
        }
        
        int data[];
        
        public ArrayBinaryTree(int data[])
        {
            this.data=data;
        }
        
        //重载frontShow函数,0代表的是index
        public void frontShow() 
        {
            frontShow(0);
        }
        
        //前序遍历
        public void frontShow(int index) 
        {
            if(data==null||data.length==0)
            {
                return;
            }
            //遍历当前节点的内容
            System.out.print(data[index]);
            //处理左子树-----data[2*index+1]
            if(2*index+1<data.length) 
            {
                frontShow(2*index+1);
            }
            //处理右子树
            if(2*index+2<data.length) 
            {
                frontShow(2*index+2);
            }
            
        }
        //重载midShow函数,0代表的是index
        public void midShow() 
        {
            midShow(0);
        }
        
        //中序遍历
        public void midShow(int index) 
        {
            if(data==null||data.length==0)
            {
                return;
            }
            //处理左子树-----data[2*index+1]
            if(2*index+1<data.length) 
            {
                midShow(2*index+1);
            }
            
            //遍历当前节点的内容
            System.out.print(data[index]);
            //处理右子树
            if(2*index+2<data.length) 
            {
                midShow(2*index+2);
            }

        }
        //重载afterShow函数,0代表传入的index
        public void afterShow() 
        {
            afterShow(0);
        }
        //后序遍历
        public void afterShow(int index) 
        {
            if(data==null||data.length==0)
            {
                return;
            }
            //处理左节点
            if(2*index+1<data.length) 
            {
                afterShow(2*index+1);
            }
            //处理右节点
            if(2*index+2<data.length)
            {
                afterShow(2*index+2);
            }
            //遍历当前的节点
            System.out.print(data[index]);
        }
}
发布了98 篇原创文章 · 获赞 34 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_42133768/article/details/86773882