题解 | #二叉树遍历#
二叉树遍历
https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef
import java.lang.String;
import java.util.Scanner;
class TreeNode{
public char val;
public TreeNode left;
public TreeNode right;
public TreeNode(char val){
this.val=val;
}
}
// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
public static int i=0;
public static TreeNode createTree(String str){
TreeNode root=null;
if(str.charAt(i)!='#'){
root=new TreeNode(str.charAt(i));
i++;
root.left=createTree(str);
root.right=createTree(str);
}else{
i++;//就继续往下走
}
return root;
}
public static void inorder(TreeNode root){
if(root==null){
return;
}
inorder(root.left);
System.out.print(root.val+" ");
inorder(root.right);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
// 注意 hasNext 和 hasNextLine 的区别
while (in.hasNextLine()) { // 注意 while 处理多个 case
String str=in.nextLine();
TreeNode root= createTree(str);
inorder(root);
}
}
}
思路:
看到这道题最好画出图去理解
其实输入就是这课二叉树的前序遍历,输出中序遍历,那可以先搭好框架,即value值和左右节点,然后根据给的字符串去创建一棵二叉树,这里别忘了字符串的charAt方法,在遍历的过程中遇到#就是空树,啥也不做,i++,继续往后遍历,
那一般情况下,定义root去接收,left和right同样的递归调用即可,一棵树创建好了,最后写出中序遍历的代码也是递归,在main方法中调用中序遍历即可
#二叉树的递归套路##我的实习求职记录#