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

相关推荐

头像
点赞 评论 收藏
转发
点赞 评论 收藏
转发
牛客网
牛客企业服务