.
题目
Given the root of a binary tree, construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way, and return it.
Omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree.
Example 1:
Input: root = [1,2,3,4]
Output: “1(2(4))(3)”
Explanation: Originallay it needs to be “1(2(4)())(3()())”, but you need to omit all the unnecessary empty parenthesis pairs. And it will be “1(2(4))(3)”
Example 2:
Input: root = [1,2,3,null,4]
Output: “1(2()(4))(3)”
Explanation: Almost the same as the first example, except we cannot omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.
Constraints:
The number of nodes in the tree is in the range [1, 10^4].
-1000 <= Node.val <= 1000
.
思路
这是一道简单题。输入一颗二叉树根节点,输出这个二叉树的前序遍历结果。对每个树节点来说,
- 如果它为空,则直接返回一对括号"()";
- 如果它的左右节点都为空,则只需返回它的值root->val;
- 如果只有它的左节点为空,为了消除输出的字符串序列的歧义性,则需要将左节点标注为"()",然后继续遍历右子树;
- 如果只有它的右节点为空,则仅需要遍历左子树即可;
- 若它的左右节点都不为空,则需要先遍历左子树,再遍历右子树。
值得注意的是,每次都要输出当前节点的值,root->val。
.
代码
/**
* 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* root) {
if (root == NULL)
return "()";
if (root->left == NULL && root->right == NULL)
{
string res = to_string(root->val);
return res;
}
string tmp = "";
if (root->left == NULL) // root->right != NULL
{
tmp += to_string(root->val) + "()";
tmp += "(" + tree2str(root->right) + ")";
}
if (root->right == NULL) // root->left != NULL
{
tmp += to_string(root->val);
tmp += "(" + tree2str(root->left) + ")";
}
if (root->left != NULL && root->right != NULL)
{
tmp += to_string(root->val);
tmp += "(" + tree2str(root->left) + ")";
tmp += "(" + tree2str(root->right) + ")";
}
return tmp;
}
};
.
后记
以上代码按照解题思路完成,当然还有优化空间。目前的答案仅超过70%的C++代码。