https://leetcode.com/problems/construct-string-from-binary-tree/
日期 | 是否一次通过 | comment |
---|---|---|
2019-01-20 02:38 | 否 | 对何时加() 理解不够清楚 |
(来源:https://leetcode.com/problems/construct-string-from-binary-tree/)
- 非递归:TODO;
- 递归:preOrder,处理好何时加上
()
1. 非递归
2.递归
class Solution {
public String tree2str(TreeNode t) {
if(t == null) {
return "";
}
StringBuilder sb = new StringBuilder();
helper(t, sb);
return sb.toString();
}
private void helper(TreeNode t, StringBuilder sb) {
if(t == null) {
return;
}
sb.append(t.val);
if(t.left != null || t.right != null) {
sb.append("(");
helper(t.left, sb);
sb.append(")");
if(t.right != null) {
sb.append("(");
helper(t.right, sb);
sb.append(")");
}
}
}
}
网友评论