二叉树遍历
二叉树遍历
题目描述
编一个程序,读入用户输入的一串先序遍历字符串,根据此字符串建立一个二叉树(以指针方式存储)。 例如如下的先序遍历字符串: ABC##DE#G##F### 其中“#”表示的是空格,空格字符代表空树。建立起此二叉树以后,再对二叉树进行中序遍历,输出遍历结果。
输入描述:
输入包括1行字符串,长度不超过100。
输出描述:
可能有多组测试数据,对于每组数据,
输出将输入字符串建立二叉树后中序遍历的序列,每个字符后面都有一个空格。
每个输出结果占一行。
示例1
输入
[复制](javascript:void(0)😉
abc##de#g##f###
输出
[复制](javascript:void(0)😉
c b e g d f a
本题不难,但是有几个要注意的地方:
- 格式化输出的函数叫printf,格式化输出字符为%c
import java.util.*;
public class Main{
public static int index=0;
private static class Node{
public char val;
public Node leftChild,rightChild;
public Node(char val,Node leftChild,Node rightNode){
this.val=val;
this.leftChild=leftChild;
this.rightChild=rightChild;
}
public Node(){;}
}
public static void main(String[]args){
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
String frontLoop=sc.next();
if(frontLoop.equals(" ")){
return;
}
Node root=buildTree(frontLoop);
printMid(root);
}
}
private static void printMid(Node node){
if(node==null){
return;
}
printMid(node.leftChild);
System.out.printf("%c ",node.val);
printMid(node.rightChild);
}
private static Node buildTree(String frontLoop){
if(index>=frontLoop.length()){
return null;
}
char thisChar=frontLoop.charAt(index);
if(thisChar=='#'){
return null;
}
Node thisNode=new Node();
thisNode.val=thisChar;
index++;
thisNode.leftChild=buildTree(frontLoop);
index++;
thisNode.rightChild=buildTree(frontLoop);
return thisNode;
}
}

浙公网安备 33010602011771号