0%

construct-string-from-binary-tree

Construct String from Binary Tree – LeetCode 606

Problem

Description

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

The null node needs to be represented by empty parenthesis pair “()”. And you need to omit all the empty parenthesis pairs that don’t affect the one-to-one mapping relationship between the string and the original binary tree.

Answer

Original

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* 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){
string ans;
ans += to_string(t->val);
if(t->left || t->right) ans += "(" + tree2str(t->left) + ")";
if(t->right) ans += "(" + tree2str(t->right) + ")";
return ans;
} else
return string();
}
};

思路

简单的前序遍历返回要求值。时间复杂度$O(n)$,空间复杂度$O(n)$。
耗时$12$ ms,排名$54.39\%$

Better

思路

还没看到更好的思路