aboutsummaryrefslogtreecommitdiff
path: root/construct_string_binary_tree.cpp
blob: a63e3c9c4f4fe37f07fba206295c86c566959def (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include "leetcode.h"

class Solution {
public:
  string tree2str(TreeNode *root) {
    if (!root)
      return "";
    string ans = to_string(root->val);
    if (root->left || root->right) {
      ans.push_back('(');
      ans += tree2str(root->left);
      ans.push_back(')');
    }
    if (root->right) {
      ans.push_back('(');
      ans += tree2str(root->right);
      ans.push_back(')');
    }
    return ans;
  }
};