笔试题不会写输入输出警告⚠️ 好无语
java:
class Solution {
public String tree2str(TreeNode root) {
if(root == null){
return "";
}
if(root.left == null && root.right == null){
return Integer.toString(root.val);
}
if(root.right == null){
return new StringBuffer().append(root.val).append("(").append(tree2str(root.left)).append(")").toString();
}
return new StringBuffer().append(root.val).append("(").append(tree2str(root.left)).append(")(").append(tree2str(root.right)).append(")").toString();
}
}
python3:
class Solution:
def tree2str(self, root: Optional[TreeNode]) -> str:
if root is None:
return ""
if root.left is None and root.right is None:
return str(root.val)
if root.right is None:
return f"{root.val}({self.tree2str(root.left)})"
return f"{root.val}({self.tree2str(root.left)})({self.tree2str(root.right)})"