标题:二叉树遍历 | 时间限制:1秒 | 内存限制:65536K | 语言限制:不限  根据给定的二叉树结构描述字符串,输出该二叉树按照中序遍历结果字符串。中序遍历顺序为:左子树,根结点,右子树。 import java.util.Scanner;public class Main {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        String str = in.nextLine();        StringBuilder sb = new StringBuilder();        temp(str, sb);        System.out.println(sb.toString());    }    public static void temp(String str, StringBuilder sb) {        if (str.contains("{")) {            String mid = str.substring(0,1);            String child = str.substring(2,str.length()-1);            String left = "";            String right = "";            if (child.contains(",")) {                if (',' == child.charAt(0)) {                    left = "";                    right = child.substring(1);                }else {                    if (',' == child.charAt(1)) {                        left = child.substring(0,1);                        right = child.substring(2);                    } else {                        char[] chars = child.toCharArray();                        int j = 1;                        for (int i = 2; i < chars.length; i++) {                            if ('{' == chars[i]) {                                j++;                            }                            if ('}' == chars[i]) {                                j--;                            }                            if (j == 0) {                                j = i;                                continue;                            }                        }                        left = child.substring(0, j+1);                        if (j == child.length() - 1) {                            right = "";                        }else                        {                            right = child.substring(j+2);                        }                    }                }            } else {                left = child;                right = "";            }            temp(left, sb);            sb.append(mid);            temp(right, sb);        } else {            sb.append(str);        }    }}
点赞 0
评论 0
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务