二叉树
前序遍历: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);
}
}
}
}