According to the post-order and in-order traversal sequences of the binary tree, the hierarchical traversal sequence is obtained

1. Topic

There is a binary tree where each node is identified by a capital letter. There are two sets of letters, which respectively represent the results of post-order traversal and in-order traversal. Please output the results of hierarchical traversal.

Input description: Enter the first line sequence, which means post-order traversal (left child -> right child -> root node);

Enter the second line sequence, which means in-order traversal (left child -> root node -> right child).

Output Description
Outputs the result of the hierarchy traversal.

Example:
Enter
CBEFDA

CBAEDF

Output
ABDCEF

2. Analysis

1) The last one of the post-order traversal must be the root node

2) Confirm the position of the root node obtained in 1) in the in-order traversal. The left side of the node is the left subtree of the new binary tree with it as the root node, and the right side of the node is the new binary tree with it as the root node. right subtree.

3) Subsequent traversal obtains that the left side of the root node is all its left and right subtree nodes

3.Java language solution:

public static void od007(){
   Scanner scanner=new Scanner(System.in);
   List<String> hou=Arrays.stream(scanner.nextLine().split("")).collect(Collectors.toList());
   List<String> zhong=Arrays.stream(scanner.nextLine().split("")).collect(Collectors.toList());
   scanner.close();
   String gen=hou.get(hou.size()-1);
   LinkedList<String> queue=new LinkedList<>();
   queue.add(gen);
   String result="";
   while (queue.size()!=0){
       String start=queue.getFirst();
       int startIndex=zhong.indexOf(start);
       List<String> zhongLeft=new ArrayList<>();
       for (int i=0;i<startIndex;i++){
           zhongLeft.add(i,zhong.get(i));
       }
       List<String> zhongRight=new ArrayList<>();
       for (int i=startIndex+1;i<zhong.size();i++){
           zhongRight.add(zhong.get(i));
       }
       int startIndex2=hou.indexOf(start);
       List<String> houLeft=new ArrayList<>();
       for (int i=0;i<startIndex2;i++){
           if (zhongLeft.contains(hou.get(i))){
               houLeft.add(i,hou.get(i));
           }
       }
       List<String> houRight=new ArrayList<>();
       for (int i=0;i<startIndex2;i++){
           if (zhongRight.contains(hou.get(i))) houRight.add(hou.get(i));
       }
       if (houLeft.size()!=0&&!result.contains(houLeft.get(houLeft.size()-1))){
           queue.add(houLeft.get(houLeft.size()-1));
       }
       if (houRight.size()!=0&&!result.contains(houLeft.get(houLeft.size()-1))){
           queue.add(houRight.get(houRight.size()-1));
       };
       result=result+start;
       queue.removeFirst();
   }
   System.out.println(result);
}

 

Guess you like

Origin blog.csdn.net/qq_43780761/article/details/126863104