Leetcode606. Construct String from Binary Tree
Leetcode606. Construct String from Binary Tree
递归方法可以一行完成,迭代方法比较麻烦。复杂度不佳,尚待提高。
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
string tree2str(TreeNode* t) {
/*
* Recursion
* Runtime: 40 ms, 27.31%
* Memory Usage: 27.3 MB, 33.33%
*/
if (t == NULL) return "";
if (t->left == NULL && t->right == NULL)
return to_string(t->val) + "";
else if (t->right == NULL)
return to_string(t->val) + "(" + tree2str(t->left) +")";
else
return to_string(t->val) + "(" + tree2str(t->left) +")" + "(" + tree2str(t->right) + ")";
}
string tree2str_iter(TreeNode* t) {
/*
* Iteration
* Runtime: 84 ms, 5.28%
* Memory Usage: 266.5 MB, 33.33%
*/
if (t == NULL) return "";
stack<TreeNode*> stack;
unordered_map<TreeNode*, bool> visited;
string str;
stack.push(t);
while (!stack.empty()) {
TreeNode* cur = stack.top();
auto it = visited.find(cur);
if (it != visited.end()) {
stack.pop();
str += ")";
}
else {
visited[cur] = true;
str = str + "(" + to_string(cur->val);
if (!cur->left && cur->right)
str += "()";
if (cur->right)
stack.push(cur->right);
if (cur->left)
stack.push(cur->left);
}
}
return str.substr(1, str.size()-2);
}
};