/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ classSolution{ int index; public TreeNode recoverFromPreorder(String S){ index = 0; return helper(S, 0); }
public TreeNode helper(String S, int depth){ //字符串遍历完 if(index > S.length()) returnnull; int curDepth = 0; int k = index; //计算当前结点的深度 while(k < S.length() && S.charAt(k) == '-'){ ++curDepth; ++k; } //当前结点深度与期望深度不符合,为路径中某结点的右子结点,返回空。 if(curDepth != depth)returnnull; index = k; int val = 0; //计算结点数值 while(index < S.length() && Character.isDigit(S.charAt(index))){ val = val * 10 + (S.charAt(index) - '0'); ++index; } //建立结点并递归建立该结点的子节点 TreeNode node = new TreeNode(val); node.left = helper(S, depth + 1); node.right = helper(S, depth + 1); return node; } }