二叉树遍历

标题:二叉树遍历 | 时间限制: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);
        }

    }
}


全部评论

相关推荐

代码飞升:别用口语,后端就写后端,前端就写前端,最后别光后悔
点赞 评论 收藏
分享
没有offer的呆呆:薪资有的时候也能说明一些问题,太少了活不活得下去是一方面,感觉学习也有限
点赞 评论 收藏
分享
评论
点赞
2
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务