606. Construct String from Binary Tree
https://leetcode.com/problems/construct-string-from-binary-tree/
/*
* @lc app=leetcode id=606 lang=cpp
*
* [606] Construct String from Binary Tree
*/
// @lc code=start
/**
* 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 == nullptr) return "";
string res;
res += to_string(t->val);
if (t->left != nullptr) res += "(" + tree2str(t->left) + ")";
if (t->right != nullptr) {
if (t->left == nullptr) res += "()";
res += "(" + tree2str(t->right) + ")";
}
return res;
}
};
// @lc code=end
Last updated