apply


私信TA

用户名:uq_71543461426

访问量:1206

签 名:

等  级
排  名 3609
经  验 1809
参赛次数 0
文章发表 6
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

TA的其他文章

参考代码:

import java.util.*;

public class Main {
    static char[] preorder;
    static char[] inorder;
    class Node{
        char val;
        Node left;
        Node right;
        Node(char val) {
            this.val = val;
        }
    }
	public static void main(String[] args) {
		Scanner scanner = new Scanner(System.in);
		while (scanner.hasNext()) {
			preorder = scanner.nextLine().toCharArray();
			inorder = scanner.nextLine().toCharArray();
			Node root = build(0, preorder.length - 1, 0, inorder.length - 1);
			print(root);
			System.out.println();
			
		}
	}
	public static void print(Node root) {
	    if(root == null) return;
	    if(root.left != null) print(root.left);
	    if(root.right != null) print(root.right);
	    System.out.print(root.val);
	}
	public static Node build(int l1, int r1, int l2, int r2) {
	    if(l1 > r1) return null;
	    Node root = new Main().new Node(preorder[l1]);
	    int mid = l2;
	    while(inorder[mid] != root.val) mid++;
	    root.left = build(l1 + 1, mid - l2 + l1, l2, mid - 1);
	    root.right = build(mid - l2 + l1 + 1, r1, mid + 1, r2);
	    return root;
	}
}


 

0.0分

0 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区