# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def tree2str(self, t: TreeNode) -> str:
if not t:
return ""
left = self.tree2str(t.left)
right = self.tree2str(t.right)
if not t.left and not t.right:
return str(t.val)
if not t.right:
return f"{t.val}({left})"
return f"{t.val}({left})({right})"
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
string tree2str(TreeNode* t) {
if (!t) return "";
string left = tree2str(t->left);
string right = tree2str(t->right);
if (!t->left && !t->right)
return to_string(t->val);
if (!t->right)
return to_string(t->val) + "(" + left + ")";
return to_string(t->val) + "(" + left + ")(" + right + ")";
}
};
// Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
public String tree2str(TreeNode t) {
if (t == null) return "";
String left = tree2str(t.left);
String right = tree2str(t.right);
if (t.left == null && t.right == null)
return String.valueOf(t.val);
if (t.right == null)
return t.val + "(" + left + ")";
return t.val + "(" + left + ")(" + right + ")";
}
}
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} t
* @return {string}
*/
var tree2str = function(t) {
if (!t) return "";
let left = tree2str(t.left);
let right = tree2str(t.right);
if (!t.left && !t.right) return t.val.toString();
if (!t.right) return t.val + "(" + left + ")";
return t.val + "(" + left + ")(" + right + ")";
};
()
immediately after the node's value.()
immediately after the left subtree string.()
to indicate the missing left child.You are guaranteed that there is only one valid string for each tree, and you should not reuse any elements from the input tree.
null
, return an empty string.
null
, return the node's value as a string.
This approach ensures that the output string is minimal yet uniquely maps back to the original tree structure. Recursion is used because each subtree can be represented in the same way as the whole tree.
Consider the following binary tree:
1 / \ 2 3 \ 4
2()(...)
.2()(4)
.1(2()(4))(3)
This string uniquely and minimally represents the tree structure.