小米,二叉树中序遍历
static String solution(String input) {
if(input.length()<=1) return input;
Stack<Object> stack=new Stack<>();
for(int i=0;i<input.length();i++){
if(stack.isEmpty()||input.charAt(i)!=')'){
stack.add(input.charAt(i));
}
else{
String res="";
TreeNode left=null;
TreeNode right=null;
while (!stack.isEmpty()){
Object tmp=stack.pop();
if(tmp instanceof TreeNode){
if(right!=null){
left=(TreeNode)tmp;
}
else right=(TreeNode)tmp;
}
else{
char c=(Character)tmp;
if(c=='(') break;
res+=c;
}
}
TreeNode cur=new TreeNode((Character)stack.pop()-'0');
String[] tmp=res.split(",");
if(tmp.length>1&&tmp[1].length()>0){
cur.left=new TreeNode(tmp[1].charAt(0)-'0');
}else if(left!=null){
cur.left=left;
}
if(tmp.length>0&&tmp[0].length()>0){
cur.right=new TreeNode(tmp[0].charAt(0)-'0');
}else if(right!=null){
cur.right=right;
}
stack.add(cur);
}
}
return getAns((TreeNode)stack.pop());
}
public static String getAns(TreeNode root) {
if (root == null) return "";
String result = "";
result+=getAns(root.left)+root.val+getAns(root.right);
return result;
} #笔试题目##小米#