import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
class TreeNode{
private String data;
private TreeNode leftNode;
private TreeNode rightNode;
public boolean hasVisited=false;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public TreeNode getLeftNode() {
return leftNode;
}
public void setLeftNode(TreeNode leftNode) {
this.leftNode = leftNode;
}
public TreeNode getRightNode() {
return rightNode;
}
public void setRightNode(TreeNode rightNode) {
this.rightNode = rightNode;
}
}
public class Tree {
public static TreeNode root=new TreeNode();
public TreeNode createTree(TreeNode node){
String ch = new Scanner(System.in).nextLine();
if (ch.equals("#")) {
return null;
}
node = new TreeNode();
node.setData(ch);
node.setLeftNode(createTree(node.getLeftNode()));
node.setRightNode(createTree(node.getRightNode()));
return node;
}
public TreeNode createT(TreeNode node){
Queue queue = new LinkedList<>();
TreeNode root;
String ch = new Scanner(System.in).nextLine();
if (ch.equals("#")) {
return null;
}
node = new TreeNode();
root = node;
node.setData(ch);
queue.offer(node);
TreeNode currentNode;
while((queue.size()>0)&&(currentNode = (TreeNode)queue.poll())!=null){
System.out.println("输入左孩子");
ch = new Scanner(System.in).nextLine();
if (!ch.equals("#")) {
node = new TreeNode();
node.setData(ch);
currentNode.setLeftNode(node);
queue.offer(node);
}
System.out.println("输入右孩子");
ch = new Scanner(System.in).nextLine();
if (!ch.equals("#")) {
node = new TreeNode();
node.setData(ch);
currentNode.setRightNode(node);
queue.offer(node);
}
}
return root;
}
public void readTree1(TreeNode root){
if(root==null){
return;
}
System.out.println(root.getData());
readTree1(root.getLeftNode());
readTree1(root.getRightNode());
}
public void readTree2(TreeNode node){
Stack stack = new Stack<>();
TreeNode currentNode= node;
while(currentNode!=null||stack.size()>0){
while(currentNode!=null){
stack.push(currentNode);
currentNode = currentNode.getLeftNode();
}
currentNode = (TreeNode)stack.pop();
System.out.println(currentNode.getData());
currentNode = currentNode.getRightNode();
}
}
public void readTree3(TreeNode node){
Stack stack = new Stack<>();
TreeNode currentNode= node;
while(currentNode!=null||stack.size()>0){
while(currentNode!=null){
stack.push(currentNode);
currentNode = currentNode.getLeftNode();
}
currentNode = (TreeNode)stack.pop();
if(currentNode.hasVisited == false){
currentNode.hasVisited=true;
stack.push(currentNode);
currentNode = currentNode.getRightNode();
}else{
System.out.println(currentNode.getData());
currentNode = null;
}
}
}
public static void main(String[] args) {
Tree tree = new Tree();
root = tree.createT(root);
tree.readTree3(root);
}
}