ZigZagging on a Tree二叉树蛇形层次遍历(Java语言)

简介: ZigZagging on a Tree二叉树蛇形层次遍历(Java语言)

题目描述:

Suppose that all the keys in a binary tree are distinct positive integers. A unique binary tree can be determined by a given pair of postorder and inorder traversal sequences. And it is a simple standard routine to print the numbers in level-order. However, if you think the problem is too simple, then you are too naive. This time you are supposed to print the numbers in “zigzagging order” – that is, starting from the root, print the numbers level-by-level, alternating between left to right and right to left. For example, for the following tree you must output: 1 11 5 8 17 12 20 15.

4726b256e87946f188365e2f21fc5300.png


Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤30), the total number of nodes in the binary tree. The second line gives the inorder sequence and the third line gives the postorder sequence. All the numbers in a line are separated by a space.


Output Specification:

For each test case, print the zigzagging sequence of the tree in a line. All the numbers in a line must be separated by exactly one space, and there must be no extra space at the end of the line.


Sample Input:

8
12 11 20 17 1 15 8 5
12 20 17 11 15 8 5 1

Sample Output:

1 11 5 8 17 12 20 15

解题思路:

根据中序和后序创建二叉树,最后蛇形层次遍历(遍历一层就开始反转一次,Java中使用了LinkedList进行存储处理)

代码中有根据中序和后序创建二叉树的模板,有层次遍历的模板;

先序和中序创建二叉树的模板参考先序和中序创建二叉树

代码:

package text_9_25;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class ZigZaggingOnATree {
  public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner scanner = new Scanner(System.in);
    int n = scanner.nextInt();
    int in[] = new int[n];
    int post[] = new int[n];
    for(int i=0;i<n;i++)
      in[i] = scanner.nextInt();
    for(int i=0;i<n;i++)
      post[i] = scanner.nextInt();
    //创建二叉树
    Node root = BuildTree(in, 0, n-1, post, 0, n-1);
    
    //蛇形层次遍历
    PrintLevelOrder(root);

    
  }
  
  public static Node BuildTree(int in[],int ibegin,int iend,int post[],int pbegin,int pend) {
    if(ibegin>iend||pbegin>pend) return null;
    Node root = new Node(post[pend]);
    for(int i=ibegin;i<=iend;i++) {
      if(post[pend]==in[i]) {
        root.left = BuildTree(in, ibegin, i-1, post, pbegin, pbegin-ibegin+i-1);
        root.right = BuildTree(in, i+1, iend, post, pbegin-ibegin+i, pend-1);
      }
    }
    return root;
  }
  public static void PrintLevelOrder(Node root) {
    boolean reversed = false;//反转标志
    Queue<Node> queue = new LinkedList<>();
    queue.add(root);
    int flag=1;//用于输出格式控制
    while(!queue.isEmpty()) {
      int size = queue.size();//当前层的节点数
      LinkedList<Integer> link = new LinkedList<>();//保存当前层结果,LinkedList可以前后插入
      for(int i=0;i<size;i++) {  //对应每一层
        Node temp = queue.poll();
        if(reversed) link.add(temp.data);
        else link.addFirst(temp.data);
        
        if(temp.left!=null) queue.add(temp.left);
        if(temp.right!=null) queue.add(temp.right);
      }
//      System.out.println(size);
      for(int j=0;j<link.size();j++) {
        if(flag==1) {
          System.out.print(link.get(j));
          flag=0;
        }
        else System.out.print(" "+link.get(j));
      }
      reversed =!reversed;  //每次反转
    }
  }

}
class Node{   //树节点类
  public int data;
  public Node left;
  public Node right;
  public Node(int data){
    this.data = data;
    left = right = null;
  }
}

相关文章
|
7天前
|
存储 算法 Java
Java中,树与图的算法涉及二叉树的前序、中序、后序遍历以及DFS和BFS搜索。
【6月更文挑战第21天】Java中,树与图的算法涉及二叉树的前序、中序、后序遍历以及DFS和BFS搜索。二叉树遍历通过访问根、左、右子节点实现。DFS采用递归遍历图的节点,而BFS利用队列按层次访问。以下是简化的代码片段:[Java代码略]
16 4
|
4天前
|
算法 Java
垃圾回收机制(Garbage Collection,GC)是Java语言的一个重要特性,它自动管理程序运行过程中不再使用的内存空间。
【6月更文挑战第24天】Java的GC自动回收不再使用的内存,关注堆中的对象。通过标记-清除、复制、压缩和分代等算法识别无用对象。GC分为Minor、Major和Full类型,针对年轻代、老年代或整个堆进行回收。性能优化涉及算法选择和参数调整。
15 3
|
6天前
|
Java
Java二叉树的遍历
Java二叉树的遍历
|
10天前
|
Java 数据安全/隐私保护 开发者
Java是一种完全支持面向对象编程的语言,其面向对象特性包括封装、继承、多态和抽象等
【6月更文挑战第18天】**面向对象编程(OOP)通过对象封装状态和行为,实现问题域的抽象。Java全面支持OOP,核心特性包括**: - **封装**:保护数据安全,隐藏内部细节。 - **继承**:子类继承父类属性和行为,促进代码重用。 - **多态**:一个接口多种实现,增强灵活性和扩展性。 - **抽象**:通过接口和抽象类抽离共性,简化复杂性。 **Java的OOP便于理解和解决复杂系统问题。**
22 3
|
9天前
|
算法 搜索推荐 Java
二叉树的基本概念、常见操作以及如何使用Java代码
二叉树的基本概念、常见操作以及如何使用Java代码
10 1
|
3天前
|
Java
二叉树简单遍历、查找、删除(java)
二叉树简单遍历、查找、删除(java)
4 0
|
3天前
|
存储 Java
顺序存储二叉树(java)
顺序存储二叉树(java)
7 0
|
3天前
|
Java
二叉树线索化(java)
二叉树线索化(java)
7 0
|
10天前
|
Java 大数据 API
|
存储 Java 编译器
Java语言------图书馆管理系统(入门简略版)
Java语言------图书馆管理系统(入门简略版)
99 0
Java语言------图书馆管理系统(入门简略版)