解题思路:
注意事项:居然是两次中根遍历,笑掉我的大牙
参考代码:
import java.util.LinkedList;
import java.util.Scanner;
class TreeNode{
public char val;
public TreeNode left;
public TreeNode right;
public TreeNode(char val) {
this.val = val;
}
}
public class Main {
public static LinkedList<Character> characters = new LinkedList<>();
public static LinkedList<Character> firstRoot=new LinkedList<>();
public static LinkedList<Character> midRoot=new LinkedList<>();
public static LinkedList<Character> lastRoot=new LinkedList<>();
public static void main(String[] args) {
//1.读入输入,转成字符数组,存入list里操作方便
//2.实现二叉树创建函数
//3.实现三种遍历方式
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
char[] chars = s.toCharArray();
for (int i = 0; i < chars.length; i++) {
characters.add(chars[i]);
}
TreeNode tree = createTree();
firstRootTra(tree);
midRootTra(tree);
lastRootTra(tree);
String s1="";
String s2="";
String s3="";
for (int i = 0; i < firstRoot.size(); i++) {
s1=s1+firstRoot.get(i)+" ";
s2=s2+midRoot.get(i)+" ";
s3=s3+lastRoot.get(i)+" ";
}
System.out.println(s1);
System.out.println(s2);
System.out.println(s2);
}
public static TreeNode createTree(){
if(characters.size()==0){
return null;
}
Character first = characters.getFirst();
characters.removeFirst();
if(first==' '){
return null;
}
TreeNode root=new TreeNode(first);//创建根
root.left=createTree();//创建左子树
root.right=createTree();//创建右子树
return root;
}
public static void firstRootTra(TreeNode treeNode){
if(treeNode==null){
return;
}
//对于根节点
firstRoot.add(treeNode.val);
firstRootTra(treeNode.left);
firstRootTra(treeNode.right);
}
public static void midRootTra(TreeNode treeNode){
if(treeNode==null){
return;
}
midRootTra(treeNode.left);
midRoot.add(treeNode.val);
midRootTra(treeNode.right);
}
public static void lastRootTra(TreeNode treeNode){
if(treeNode==null){
return;
}
lastRootTra(treeNode.left);
lastRootTra(treeNode.right);
lastRoot.add(treeNode.val);
}
}
0.0分
1 人评分
C二级辅导-计负均正 (C语言代码)浏览:587 |
C语言训练-最大数问题 (C语言代码).........关于-1浏览:742 |
模拟计算器 (C语言代码)浏览:880 |
C语言程序设计教程(第三版)课后习题6.4 (C语言代码)浏览:590 |
最小公倍数 (C语言代码)浏览:862 |
C语言程序设计教程(第三版)课后习题8.3 (C语言代码)浏览:624 |
母牛的故事 (C语言代码)浏览:915 |
C语言程序设计教程(第三版)课后习题6.9 (C语言代码)浏览:762 |
简单的a+b (C语言代码)浏览:335 |
C语言程序设计教程(第三版)课后习题3.7 (C语言代码)浏览:840 |