weekly test 35的第二题,easy的,但我没做出来;一方面不太理解题目的one-to-one mapping是什么意思(现在理解的是,如果左孩子没有 右孩子有的情况,就保留左孩子的空braces,否则无法区分右孩子),一方面实在怕了递归了。
答案:
public String tree2str(TreeNode t) {
return preOrder(t);
}
private String preOrder(TreeNode t) {
if (t == null)
return "";
//右孩子是空的情况,为了避免加括号,避免preorder右孩子
if (t.left != null && t.right == null) {
return t.val + "(" + preOrder(t.left) + ")";
}
if (t.left == null && t.right == null) {
return t.val + "";
}
return t.val + "(" + preOrder(t.left) + ")(" + preOrder(t.right) + ")";
}
或者:
https://discuss.leetcode.com/topic/91311/java-simple-recursion
public String tree2str(TreeNode t) {
StringBuilder sb = new StringBuilder();
helper(sb,t);
return sb.toString();
}
public void helper(StringBuilder sb,TreeNode t){
if(t!=null){
sb.append(t.val);
if(t.left!=null||t.right!=null){
sb.append("(");
helper(sb,t.left);
sb.append(")");
if(t.right!=null){
sb.append("(");
helper(sb,t.right);
sb.append(")");
}
}
}
}
或者:
public class Solution {
public String tree2str(TreeNode t) {
if (t == null) return "";
String result = t.val + "";
String left = tree2str(t.left);
String right = tree2str(t.right);
if (left == "" && right == "") return result;
if (left == "") return result +"()" + "(" + right + ")";
if (right == "") return result + "(" + left + ")";
return result + "(" + left + ")" + "(" + right + ")";
}
}