Get preamble sequence and the sequences in the sequence of subsequent binary sequences

Binary tree traversal Three common are: preorder (ABC), preorder (BAC), post-order traversal (BCA)

 Preorder:

   If the binary tree is empty, empty; otherwise:

  1. Access root node;
  2. Preorder left subtree;
  3. Preorder right subtree.

 Preorder:

   If the binary tree is empty, empty; otherwise:

  1. Preorder left subtree;
  2. Access root node;
  3. Preorder right subtree.

 Postorder:

   If the binary tree is empty, empty; otherwise:

  1. After traversing the left subtree order;
  2. Postorder right subtree;
  3. Root access.

In the learning is determined according to the binary tree traversal sequence , the know: can be uniquely identified by a binary or after the first binary tree traversal sequence.

The description uses the algorithm based on the java code traversal sequence preorder traversal to obtain the code sequence:

. 1  Package learn.normalcode;
 2  
. 3  Import of java.util.ArrayList;
 . 4  
. 5  public  class BlankD {
 . 6      public  static the ArrayList <Character> = ansList new new the ArrayList <> (. 11 );
 . 7      // in sequence and the subsequent sequence of binary tree by before the acquisition sequence motif sequence 
. 8      public  static  void getAns (Middle String, String back) {
 . 9          // after the last sequence is a sequence node is the root node 
10          int backLength back.length = (), = middleLength middle.length () ;
 . 11          char C = '#' ;
 12 is          IF(backLength> 0 ) {
 13 is              C = back.charAt (backLength -. 1 );
 14              ansList.add (C);
 15  
16              // therefrom / subsequent sequences split left and right subtree / subsequent sequences 
. 17              int indexOfRoot = middle.indexOf (C);
 18 is              getAns (middle.substring (0, indexOfRoot), back.substring (0 , indexOfRoot));
 . 19              getAns (middle.substring (+ indexOfRoot. 1, middleLength), back.substring (indexOfRoot, backLength -. 1 ));
 20 is          }
 21 is          return ;
 22 is  
23 is      }
 24      public  static  void main(String[] args) {
25         String middle = "SMBDCEAFHG", back = "MSDECBHGFA";
26         getAns(middle, back);
27         System.out.println(ansList);
28 
29         ansList.clear();
30         middle = "DCBA";
31         back = "DCBA";
32         getAns(middle, back);
33         System.out.println(ansList);
34 
35         ansList.clear();
36         middle = "SMBDCEA";
37         back = "MSDECBA";
38         getAns(middle, back);
39         System.out.println(ansList);
40     }
41 }

 

Guess you like

Origin www.cnblogs.com/orzt/p/11529865.html