LeetCode Solutions
606. Construct String from Binary Tree
Time: $O(n)$ Space: $O(n)$
class Solution {
public:
string tree2str(TreeNode* t) {
return dfs(t);
}
private:
string dfs(TreeNode* root) {
if (root == nullptr)
return "";
const string& rootStr = to_string(root->val);
if (root->right)
return rootStr + "(" + dfs(root->left) + ")(" + dfs(root->right) + ")";
if (root->left)
return rootStr + "(" + dfs(root->left) + ")";
return rootStr + "";
}
};
class Solution {
public String tree2str(TreeNode t) {
return dfs(t);
}
private String dfs(TreeNode root) {
if (root == null)
return "";
if (root.right != null)
return root.val + "(" + dfs(root.left) + ")(" + dfs(root.right) + ")";
if (root.left != null)
return root.val + "(" + dfs(root.left) + ")";
return root.val + "";
}
}
class Solution:
def tree2str(self, t: Optional[TreeNode]) -> str:
def dfs(root: Optional[TreeNode]) -> str:
if not root:
return ''
if root.right:
return str(root.val) + '(' + dfs(root.left) + ')(' + dfs(root.right) + ')'
if root.left:
return str(root.val) + '(' + dfs(root.left) + ')'
return str(root.val)
return dfs(t)