606. Construct String from Binary Tree
https://leetcode.com/problems/construct-string-from-binary-tree/
二叉树表示成由()和数字组成的字符串,数字代表二叉树结点的值,数字旁边分别是左右子树,每个子树是括号括起来的递归定义的树,如果只有右子树则需要引入一个空()。根据题目规定做pre-order 遍历,返回的str外加()。
/*
* @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
Was this helpful?