本题考查
二叉树、中序遍历
思路
思路一句话:“根据二叉树中序遍历非递归代码生成二叉树并对其进行后序遍历”
如何根据二叉树中序遍历非递归代码生成二叉树?
建立两个变量preCal与pre分别记录上一次操作的类型与操作的结点索引。
分两种情况讨论:
- 如果当前操作是“push”的话
如果上一次的操作是push,则本次push结点是上个操作结点的左孩子
如果上一次的操作是pop,则本次push结点是上个pop出的结点的右孩子
- 如果当前操作是“pop”的话
更新preCal与pre的值
AC代码
import java.util.Scanner;
import java.util.Stack;
public class Main {
static String result = "";
static class Node {
int key;
Node leftChild;
Node rightChild;
public Node() {
this.key = -1;
this.leftChild = null;
this.rightChild = null;
}
}
static void postOrder(Node root) {
if(root.leftChild != null)
postOrder(root.leftChild);
if(root.rightChild != null)
postOrder(root.rightChild);
result += root.key + " ";
}
public static void main(String[] args) {
Stack<Integer> stack = new Stack<Integer>();
Scanner scaner = new Scanner(System.in);
int round = scaner.nextInt();
Node[] tree = new Node[round+1];
for (int i = 0; i < round+1; i++) {
tree[i] = new Node();
}
int pre = -1;
String preCal = "";
int root = -1;
for (int i = 0; i < 2 * round; i++) {
String cal = scaner.next();
if(cal.equals("Push")) {
int temp = scaner.nextInt();
stack.push(temp);
tree[temp].key = temp;
if(pre == -1) {
root = temp;
}
else {
if(preCal.equals("Push"))
tree[pre].leftChild = tree[temp];
else
tree[pre].rightChild = tree[temp];
}
preCal = cal;
pre = temp;
}
else {
preCal = cal;
pre = stack.pop();
}
}
scaner.close();
postOrder(tree[root]);
System.out.println(result.trim());
}
}
来源:CSDN
作者:东方旅行者
链接:https://blog.csdn.net/qq_43270828/article/details/104295990