一刷
注意如果root.right是null的话不需要加额外的"()"
85.54 %
class Solution {
public String tree2str(TreeNode t) {
StringBuilder sb = new StringBuilder();
//TODO
helper(t, sb);
return sb.toString();
}
private void helper(TreeNode root, StringBuilder sb) {
if (root == null) return;
sb.append(root.val);
if (root.left == null && root.right == null) return;
sb.append("(");
helper(root.left, sb);
sb.append(")");
if (root.right != null) {
sb.append("(");
helper(root.right, sb);
sb.append(")");
}
}
}
二刷
90.49 %
class Solution {
public String tree2str(TreeNode t) {
StringBuilder sb = new StringBuilder();
dfsHelper(t, sb);
return sb.toString();
}
private void dfsHelper(TreeNode t, StringBuilder sb) {
if (t == null) return;
sb.append(t.val);
if (t.left == null && t.right == null) return; // t is leaf
sb.append("(");
dfsHelper(t.left, sb);
sb.append(")");
if (t.right == null) return;
sb.append("(");
dfsHelper(t.right, sb);
sb.append(")");
}
}
No comments:
Post a Comment