其他分享
首页 > 其他分享> > 数组转二叉树前中后序打印

数组转二叉树前中后序打印

作者:互联网

package digui;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author yuchen
 * @version 1.0
 * @date 2020-01-21 14:53
 */
public class 数组转二叉树前中后序打印 {

    public static void main(String[] args) {
        int[] array = {10, 5, 15, 3, 7, 0, 18};
        TreeNode treeNode = createTree(array);
        TreeOperation.show(treeNode);
        beforeSort(treeNode);
        System.out.println("===========");
        middleSort(treeNode);
        System.out.println("===========");
        afterSort(treeNode);
    }

    public static TreeNode createTree(int array[]) {
        List<TreeNode> treeNodeList = new ArrayList<>();

        Arrays.stream(array).forEach((a) -> {
            TreeNode treeNode = new TreeNode(a, null, null);
            treeNodeList.add(treeNode);
        });


        if (treeNodeList.size() > 0) {
            for (int i = 0; i < array.length / 2 - 1; i++) {

                if (treeNodeList.get(2 * i + 1) != null) {
                    treeNodeList.get(i).left = treeNodeList.get(2 * i + 1);
                }

                if (treeNodeList.get(2 * i + 2) != null) {
                    treeNodeList.get(i).right = treeNodeList.get(2 * i + 2);
                }
            }
        }

        int lastIndex = array.length / 2 - 1;
        treeNodeList.get(lastIndex).left = treeNodeList.get(2 * lastIndex + 1);

        if (array.length % 2 == 1) {
            treeNodeList.get(lastIndex).right = treeNodeList.get(2 * lastIndex + 2);
        }

        return treeNodeList.get(0);
    }

    /**
     * 前序打印二叉树
     */
    public static void beforeSort(TreeNode treeNode){
        if(treeNode!=null){
            System.out.println(treeNode.val);
            beforeSort(treeNode.left);
            beforeSort(treeNode.right);
        }
    }

    /**
     * 中序打印二叉树
     */
    public static void middleSort(TreeNode treeNode){
        if(treeNode!=null){
            middleSort(treeNode.left);
            System.out.println(treeNode.val);
            middleSort(treeNode.right);
        }
    }

    /**
     * 后序打印二叉树
     */
    public static void afterSort(TreeNode treeNode){
        if(treeNode!=null){
            afterSort(treeNode.left);
            afterSort(treeNode.right);
            System.out.println(treeNode.val);
        }
    }
}

打印结果:

      10     
    /   \    
  5       15 
 / \     / \ 
3   7   0   18
10
5
3
7
15
0
18
===========
3
5
7
10
0
15
18
===========
3
7
5
0
18
15
10

这瓜保熟么 发布了150 篇原创文章 · 获赞 96 · 访问量 22万+ 私信 关注

标签:treeNode,get,前中,后序,二叉树,treeNodeList,TreeNode,array,null
来源: https://blog.csdn.net/luzhensmart/article/details/104063593