Leetcode 606 Solution

This article provides solution to leetcode question 606 (construct-string-from-binary-tree)

https://leetcode.com/problems/construct-string-from-binary-tree

Solution

/** * 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 { string ans; public: void _tree2str(TreeNode* t) { if (t == NULL) return;
ans += to_string(t->val);
if (t->left || t->right) { ans += "("; _tree2str(t->left); ans += ")"; }
if (t->right) { ans += "("; _tree2str(t->right); ans += ")"; } }
string tree2str(TreeNode* t) { _tree2str(t); return ans; } };