链接:
思路
使用二叉树的中序遍历,需要注意的是当左节点为空,右节点不为空的时候要加上()。
代码
class Solution {
public:
string tree2str(TreeNode* root) {
if (root == nullptr)
return nullptr;
string str;
str += to_string(root->val);// 处理根节点
if (root->left)
{
str += '(';
str += tree2str(root->left);// 左子树
str += ')';
}
if (root->left == nullptr && root->right)
{
str += '(';
str += ')';
}
if (root->right)
{
str += '(';
str += tree2str(root->right);// 右子树
str += ')';
}
return str;
}
};