LeetCode | 606. Construct String from Binary Tree 根据二叉树构建字符串

.

题目

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

.

思路

这是一道简单题。输入一颗二叉树根节点,输出这个二叉树的前序遍历结果。对每个树节点来说,

  1. 如果它为空,则直接返回一对括号"()";
  2. 如果它的左右节点都为空,则只需返回它的值root->val;
  3. 如果只有它的左节点为空,为了消除输出的字符串序列的歧义性,则需要将左节点标注为"()",然后继续遍历右子树;
  4. 如果只有它的右节点为空,则仅需要遍历左子树即可;
  5. 若它的左右节点都不为空,则需要先遍历左子树,再遍历右子树。

值得注意的是,每次都要输出当前节点的值,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++代码。

.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值