【牛客网】KY11 二叉树遍历-CSDN博客

58 阅读1分钟

二叉树遍历

题目

在这里插入图片描述
题目很简单 就是根据他给出的先序遍历创建出二叉树在中序遍历二叉树

思路

递归创建在打印

代码

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 void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        while (in.hasNextLine()) { // 注意 while 处理多个 case
        //这里使用hasNextLine
            String str = in.nextLine();
            TreeNode root = createTree(str);
            inOrder(root);
        }
    }
    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);
            //创建顺序为root -> 左节点 ->右节点
            //因为题目中给的是前序遍历的结果
            //如果给其他顺序遍历的结果只需要修改root的创建和左节点和右节点的递归的 顺序
        }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);
        //中序遍历
    }

}