本文主要是介绍根据前序遍历和中序遍历生成二叉树,并层序遍历输出二叉树,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
二叉树
前序遍历:ABDFCEGH
中序遍历:BFDAGEHC
演示
代码:
package com.fdw.algorithm.hhh;import com.fdw.algorithm.structure.TreeNode;import java.util.LinkedList;
import java.util.Queue;/*** @description:* @author: ThatMonth* @create: 2024-08-20 13:54**/
public class Test55 {public static void main(String[] args) {//前序遍历String beforeOrder = "ABDFCEGH";//中序遍历String midOrder = "BFDAGEHC";//构建二叉树TreeNode execute = execute(beforeOrder, midOrder, 0, beforeOrder.length() - 1, 0, midOrder.length() - 1);//层序遍历levelPrint(execute);}//中左右 左中右public static TreeNode execute(String beforeOrder,String midOrder,int bh,int bt,int mh,int mt){if(bh>bt||mh>mt){return null;}//前序第一个是顶char rootc = beforeOrder.charAt(bh);TreeNode root = new TreeNode(rootc);int midindex=mh;int temp =0;//从中序中找到顶for (int i = mh; i <= mt; i++) {if(midOrder.charAt(i)==rootc){midindex = i;break;}temp++;}root.left = execute(beforeOrder,midOrder, bh+1, bh+temp, mh, midindex-1);root.right = execute(beforeOrder,midOrder, bh+temp+1, bt, midindex+1, mt);return root;}//层序遍历public static void levelPrint(TreeNode node){Queue<TreeNode> queue =new LinkedList<>();queue.add(node);while(!queue.isEmpty()){TreeNode poll = queue.poll();System.out.print(poll.ch+" ");if(poll.left!=null){queue.offer(poll.left);}if(poll.right!=null){queue.offer(poll.right);}}}
}
这篇关于根据前序遍历和中序遍历生成二叉树,并层序遍历输出二叉树的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!