首先确定出根节点
然后确定出左右节点的字符串,把这两个字符串交给递归处理
4(2(3)(1))(6(5))
发现规律 4没有括号 直接就是最上层根节点 发现左括号前是root,
然后2(3)(1)和6(5) 成对的括号 只一个树的完整结构
代码实现结果最好debug看下 我偷懒没有打印
public class LeetCode536 {
//定义一个树结构
public static class TreeNode{
int root;
TreeNode left;
TreeNode right;
public TreeNode(int root) {
this.root = root;
}
public TreeNode(int root, TreeNode left, TreeNode right) {
this.root = root;
this.left = left;
this.right = right;
}
}
public static TreeNode strToTree(String s){
if(s==null || s.length()<1){
return null;
}
//一开始就有括号就 直接去掉
if(s.charAt(0)=='('&&s.charAt(s.length()-1)==')'){
s=s.substring(1,s.length()-1);
}
int index =0;
TreeNode treeNode=null;
//获取根节点
while (index



