Java builds a binary tree based on preorder traversal

Build a binary tree based on preorder traversal

topic description

Write a program that reads in a string of preorder traversal strings input by the user, and builds a binary tree (stored by pointers) based on the strings. For example, the following preorder traversal string: ABC##DE#G##F### where "#" represents a space, and the space character represents an empty tree. After the binary tree is established, perform an in-order traversal on the binary tree and output the traversal result.
Input description:
The input consists of 1 line of strings, the length of which does not exceed 100.
Output description:
There may be multiple sets of test data. For each set of data, output the sequence of inorder traversal after the input string is built as a binary tree. There is a space after each character. Each output takes one line.

example

insert image description here

Original title OJ link

https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef?tpId=60&&tqId=29483&rp=1&ru=/activity/oj&qru=/ta/tsing-kaoyan/question-ranking

answer

import java.util.Scanner;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
class   TreeNode{
    
    //创建一个树结点的类,这个类最后不要构建在Main类了里面,构建在里面是内部类
        char val;
        TreeNode left;
        TreeNode right;

        public TreeNode(char ch){
    
    
            this.val = ch;
            this.left = null;
            this.right = null;
        }

}
public class Main {
    
     
    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 = creatTree(str);
            midOrder(root);
        }
    }
    public static int i = 0;//必须是静态的,不然在creatTree这个静态方法里面没法用
    //构建二叉树
    public static TreeNode creatTree(String str){
    
    
        TreeNode root = null;
        if(str.charAt(i) != '#'){
    
    //只要值不是#,就证明是结点,所以先把结点创建出来
            root = new TreeNode(str.charAt(i));
            i++;
            root.left = creatTree(str);
            root.right = creatTree(str);
        }
        else{
    
    
           i++;//本题是不需要判断i是否越界的,因为只有给定的str是合法的前驱遍历,那么i就不会无限增加,因为有递归次数做保证

        }
        return root;

    }
    //中序遍历
    public static void midOrder(TreeNode root){
    
    
        if(root == null){
    
    
            return;
        }
        midOrder(root.left);
        System.out.print(root.val + " ");
        midOrder(root.right);

    }
}

Guess you like

Origin blog.csdn.net/baixian110/article/details/130954430