解题思路:
注意事项:居然是两次中根遍历,笑掉我的大牙
参考代码:
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语言程序设计教程(第三版)课后习题8.5 (C++代码)浏览:733 |
C语言训练-排序问题<1> (C语言代码)浏览:1351 |
矩形面积交 (C语言代码)浏览:1514 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:648 |
C语言程序设计教程(第三版)课后习题7.5 (C语言代码)浏览:641 |
C二级辅导-同因查找 (C语言代码)浏览:585 |
C语言程序设计教程(第三版)课后习题5.7 (C语言代码)浏览:575 |
1113题解浏览:788 |
罗列完美数 (C语言代码)浏览:491 |
1051(奇了怪了)浏览:649 |