Tree Traversals Again(Java语言)(先序和中序创建二叉树)(遍历树)

简介: Tree Traversals Again(Java语言)(先序和中序创建二叉树)(遍历树)

题目描述:

An inorder binary tree traversal can be implemented in a non-recursive way with a stack. For example, suppose that when a 6-node binary tree (with the keys numbered from 1 to 6) is traversed, the stack operations are: push(1); push(2); push(3); pop(); pop(); push(4); pop(); pop(); push(5); push(6); pop(); pop(). Then a unique binary tree (shown in Figure 1) can be generated from this sequence of operations. Your task is to give the postorder traversal sequence of this tree.


f8533843d15949c3972ab8f5cd5d5ab6.png

Figure 1

Input Specification:

Each input file contains one test case. For each case, the first line contains a positive integer N (≤30) which is the total number of nodes in a tree (and hence the nodes are numbered from 1 to N). Then 2N lines follow, each describes a stack operation in the format: “Push X” where X is the index of the node being pushed onto the stack; or “Pop” meaning to pop one node from the stack.

Output Specification:

For each test case, print the postorder traversal sequence of the corresponding tree in one line. A solution is guaranteed to exist. All the numbers must be separated by exactly one space, and there must be no extra space at the end of the line.


Sample Input:

6
Push 1
Push 2
Push 3
Pop
Pop
Push 4
Pop
Pop
Push 5
Push 6
Pop
Pop

Sample Output:

3 4 2 6 5 1

解题思路:

通过题目可以发现push是先序遍历,pop是中序遍历,然后根据先序和中序构造树,后序遍历出结果。

代码:

package text2;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Stack;

public class TreeTraversalsAgain {
  static ArrayList<Integer> post = new ArrayList<>();
  public static void main(String[] args) throws NumberFormatException, IOException {
    // TODO Auto-generated method stub
    BufferedReader read = new BufferedReader(new InputStreamReader(System.in));
    int n=Integer.parseInt(read.readLine());
    int pre[] = new int[n];
    int in[] = new int[n];
    
    Stack<Integer> stack = new Stack<>();
    for(int i=0,j=0,k=0;i<2*n;i++) {
      String[] str = read.readLine().split(" ");
      if(str[0].equals("Push")) {//前序
        pre[j]=Integer.parseInt(str[1]);
        stack.push(pre[j]);
        j++;
      }else {
        in[k]=stack.pop();
        k++;
      }
    }
    Node root = buildTree(pre, 0, n-1, in, 0, n-1);
    PrintPost(root);
//    System.out.println(post.size());
    for(int i=0;i<post.size();i++) {
      if(i==0) System.out.print(post.get(i));
      else System.out.print(" "+post.get(i));
    }
    
    
  }
  //根据前序与中序创建二叉树模板
  public static Node buildTree(int pre[],int pbegin,int pend,int in[],int ibegin,int iend) {
    if(pbegin>pend||ibegin>iend) return null;
    Node root = new Node(pre[pbegin]);//根节点
    for(int i=ibegin;i<=iend;i++) {
      if(pre[pbegin]==in[i]) {
        root.left = buildTree(pre, pbegin+1, pbegin-ibegin+i, in, ibegin, i-1);
        root.right = buildTree(pre, pbegin-ibegin+i+1, pend, in, i+1, iend);
      }
    }
    return root;
  }
  //后序遍历
  public static void PrintPost(Node root) { 
    if(root!=null) {
      PrintPost(root.left);
      PrintPost(root.right);
      post.add(root.element);
    }
  }

}
class Node{   //树节点类
  public int element; //节点值   
  public Node left;  //左右节点
  public Node right;
  
  public Node(int element) {
    // TODO Auto-generated constructor stub
    this.element = element;
    left = right = null;
  }
}

目录
相关文章
|
2月前
|
JSON JavaScript 前端开发
Python+JAVA+PHP语言,苏宁商品详情API
调用苏宁商品详情API,可通过HTTP/HTTPS发送请求并解析响应数据,支持多种编程语言,如JavaScript、Java、PHP、C#、Ruby等。核心步骤包括构造请求URL、发送GET/POST请求及解析JSON/XML响应。不同语言示例展示了如何获取商品名称与价格等信息,实际使用时请参考苏宁开放平台最新文档以确保兼容性。
|
2月前
|
监控 Java API
Java语言按文件创建日期排序及获取最新文件的技术
这段代码实现了文件创建时间的读取、文件列表的获取与排序以及获取最新文件的需求。它具备良好的效率和可读性,对于绝大多数处理文件属性相关的需求来说足够健壮。在实际应用中,根据具体情况,可能还需要进一步处理如访问权限不足、文件系统不支持某些属性等边界情况。
182 14
|
3月前
|
Java 编译器 应用服务中间件
为什么说 Java 语言编译与解释并存的原因
在编程语言的世界里,Java以其独特的“编译与解释并存”特性独树一帜。这一特性不仅赋予了Java强大的跨平台能力,还使其在性能和灵活性上达到了很好的平衡。接下来,我们将深入探讨Java语言这一特性的本质、原理以及在实际应用中的体现。
82 6
|
3月前
|
分布式计算 Java 大数据
Java 语言基础概念与常识之主要特点解析
Java是一种广泛应用于企业级开发、移动应用(如Android)、大数据处理及云计算等领域的编程语言。其核心特点包括跨平台性(一次编写,到处运行)、面向对象设计、自动垃圾回收、多线程支持和高性能表现。Java通过JVM实现跨平台,具备强大的健壮性和安全性,同时拥有丰富的标准库与活跃的开发者社区。本文深入解析Java的技术优势及其在电商系统、大数据处理和云计算中的实际应用,并提供相关面试资料供学习参考。
120 0
|
3月前
|
网络协议 安全 Java
实现Java语言的文件断点续传功能的技术方案。
像这样,我们就完成了一项看似高科技、实则亲民的小工程。这样的技术实现不仅具备实用性,也能在面对网络不稳定的挑战时,稳稳地、不失乐趣地完成工作。
226 0
|
缓存 Java 测试技术
探讨Java中遍历Map集合的最快方式
探讨Java中遍历Map集合的最快方式
290 1
|
存储 缓存 Java
Java遍历Map集合的方法
在Java中,遍历Map集合主要有四种方式:1) 使用`keySet()`遍历keys并用`get()`获取values;2) 使用`entrySet()`直接遍历键值对,效率较高;3) 通过`Iterator`遍历,适合在遍历中删除元素;4) Java 8及以上版本可用`forEach`和Lambda表达式,简洁易读。`entrySet()`通常性能最佳,而遍历方式的选择应考虑代码可读性和数据量。
223 0
Java 遍历Map集合的各种姿势
最常用,在键值都需要时使用。 Map map = new HashMap(); for (Map.Entry entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } 在for-each循环中遍历keys或values。
741 0
Java使用增强for循环和迭代器遍历Map集合
1、通过key集合访问,对Key敢兴趣,可以访问与key对应的Value值;  for(String k:maps.keySet()){             System.
1132 0
|
11天前
|
数据采集 存储 弹性计算
高并发Java爬虫的瓶颈分析与动态线程优化方案
高并发Java爬虫的瓶颈分析与动态线程优化方案