关注
import java.util.*;
public class Test{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
int index = 0, preIndex = 0;
while(s.charAt(index) != '(') //找到根节点
index++;
TreeNode root = new TreeNode(null, null, null, s.substring(0,index)), tmp = root;
index++;
preIndex = index;
char flag = '(';
while(index < s.length()) {
char c = s.charAt(index);
if(c == '(' || c == ')' || c == ',') {
if(flag == '(') {
tmp.left = new TreeNode(null, null, null, s.substring(preIndex,index));
tmp.left.father = tmp;
tmp = tmp.left;
}else if(flag == ',') {
tmp = tmp.father;
tmp.right = new TreeNode(null, null, null, s.substring(preIndex,index));
tmp.right.father = tmp;
tmp = tmp.right;
}else if(flag == ')') {
tmp = tmp.father;
}
preIndex = index+1;
flag = c;
}
index++;
}
func(root);
}
private static void func(TreeNode root) {
if(root.left != null)
func(root.left);
System.out.print(root.val);
if (root.right != null)
func(root.right);
}
}
class TreeNode{
TreeNode left,right,father;
String val;
public TreeNode(TreeNode left, TreeNode right, TreeNode father, String val) {
this.left = left;
this.right = right;
this.father = father;
this.val = val;
}
}
查看原帖
点赞 2
相关推荐
点赞 评论 收藏
转发
查看8道真题和解析 产品面经
点赞 评论 收藏
转发
牛客热帖
正在热议
# 和牛牛一起刷题打卡 #
4753次浏览 445人参与
# 机械制造薪资爆料 #
341318次浏览 4051人参与
# 牛客帮帮团来啦!有问必答 #
986500次浏览 15285人参与
# 通信硬件薪资爆料 #
242336次浏览 2283人参与
# 腾讯工作体验 #
146642次浏览 1408人参与
# 如何写一份好简历 #
301216次浏览 4329人参与
# 实习必须要去大厂吗? #
18264次浏览 265人参与
# 你的简历改到第几版了 #
323363次浏览 4858人参与
# 你觉得机械有必要实习吗 #
10221次浏览 138人参与
# 你收到了团子的OC了吗 #
515354次浏览 6136人参与
# 晒一晒我的offer #
3653286次浏览 56943人参与
# 2022毕业生求职现身说法 #
20575次浏览 310人参与
# 毕业租房也有小确幸 #
32252次浏览 1895人参与
# 产品人专业大盘点 #
15113次浏览 120人参与
# 为什么国企只招应届生 #
56176次浏览 411人参与
# 浅聊一下我实习的辛苦费 #
93479次浏览 916人参与
# 视觉/交互/设计岗位评价 #
3367次浏览 61人参与
# 产品人求职现状 #
54971次浏览 795人参与
# 为什么那么多公司毁约 #
55045次浏览 486人参与
# 找工作时遇到的神仙HR #
196539次浏览 1842人参与