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;
  }
}

相关文章
|
2月前
|
Java Maven
使用java语言制作一个窗体(弹窗),用来收集用户输入的内容
该博客文章介绍了如何使用Java Swing中的JFrame创建一个窗体来收集用户输入的内容,并提供了详细的实现步骤和完整代码示例。
使用java语言制作一个窗体(弹窗),用来收集用户输入的内容
|
3月前
|
算法 Java
Java语言实现最短路径算法(Shortest Path)
Java语言实现最短路径算法(Shortest Path)
45 3
|
2月前
|
存储 算法 Java
LeetCode经典算法题:二叉树遍历(递归遍历+迭代遍历+层序遍历)以及线索二叉树java详解
LeetCode经典算法题:二叉树遍历(递归遍历+迭代遍历+层序遍历)以及线索二叉树java详解
65 0
|
2月前
|
Rust JavaScript Java
简单对比Java、Python、Go、Rust等常见语言计算斐波拉契数的性能
简单对比Java、Python、Go、Rust等常见语言计算斐波拉契数的性能
|
3月前
|
算法 Java 编译器
透视Java语言的究极优化:探索性能的深度
在Java程序员的日常工作中,优化代码性能是一项至关重要的任务。然而,除了传统的性能调优方法外,本文将探讨一些更为深奥的技术,如JIT编译器的内部工作机制、GC算法的进阶应用以及多线程并发模型的优化策略。通过深入了解这些技术背后的原理和实现,我们可以更好地理解如何在Java平台上实现最高效的代码运行。 【7月更文挑战第11天】
67 4
|
3月前
|
Java 大数据 API
Java语言的核心知识点与特性
Java 是一种广泛使用的编程语言,自 1995 年发布以来,它已经成为了企业级应用开发、移动应用开发、大数据处理和云计算等领域的主流技术。
40 0
|
3月前
|
设计模式 算法 Oracle
Java语言学习路径及学习资源推荐
Java语言学习路径及学习资源推荐
|
存储 Java 编译器
Java语言------图书馆管理系统(入门简略版)
Java语言------图书馆管理系统(入门简略版)
106 0
Java语言------图书馆管理系统(入门简略版)
|
小程序 安全 前端开发
【Java编程进阶】Java语言基础入门篇
整个Java全栈编程知识体系十分庞大,包括JavaSE知识,Web前端,Web后端,数据库相关的知识等,初学者应该系统踏实的学习,一步一个脚印。Java语言是一种完全面向对象的跨平台语言。有很多突出的优点,例如简单易学,面向对象,分布式,安全可靠,解释型语言,跨平台运行,可移植高性能多线程,可实现网络编程等。
178 0
【Java编程进阶】Java语言基础入门篇
|
Java
Java学习路线-53:EL(表达式语言)入门及 EL 函数库
Java学习路线-53:EL(表达式语言)入门及 EL 函数库
117 0
下一篇
无影云桌面