Leetcode606. 由二叉树构建字符串

Leetcode606. Construct String from Binary Tree

题目

You need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.

The null node needs to be represented by empty parenthesis pair “()”. And you need to omit all the empty parenthesis pairs that don’t affect the one-to-one mapping relationship between the string and the original binary tree.

Example1:
Input: Binary tree: [1,2,3,4]
1
/ \
2 3
/
4
Output: “1(2(4))(3)”
Explanation: Originally 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)”.

Example2:
Input: Binary tree: [1,2,3,null,4]
1
/ \
2 3
\
4
Output: “1(2()(4))(3)”
Explanation: Almost the same as the first example, except we can’t omit the first parenthesis pair to break the one-to-one mapping relationship between the input and the output.

解题分析

题目刚拿过来一看可能会有点被吓住了,但其实静下心来思考这个问题,你会发现题目并没有想象中的难。我们先来分析题目给的两个例子,进而分析出由二叉树输出的字符串应满足的要求。

我们先看看第一个例子。根节点1有左右两个子节点2和3,其中子节点2有左子节点4,而输出的字符串为”1(2(4))(3)”。由此不难分析出:当某个节点左右两个子节点均不为空时,应加上(),并在其中加上子节点的值;而当某个节点只存在左子节点时,则可以省略右子节点对应的()。
再来看第二个例子。根节点1有左右两个子节点2和3,其中子节点2有右子节点4,而输出的字符串为”1(2()(4))(3)”。可以看出:当某个节点只存在右子节点时,则不能省略其左子节点对应的()。

分析完输出的字符串的格式要求,再来想下如何遍历二叉树。很显然,采用先序遍历的方法就可以了,在遍历的时候注意判断左右子节点是否为空,就可以顺利解决这个问题。

源代码

/**
 * 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 == NULL) {
            return "";
        }
        string str = to_string(t->val);
        if(t->left != NULL) {
            str += '(' + tree2str(t->left) + ')';
        }
        else if(t->right != NULL) {
            str += "()";
        }

        if(t->right != NULL) {
            str += '(' + tree2str(t->right) + ')';
        }
        return str;
    }
};

以上只是我对这道题的一些想法,有问题还请在评论区讨论留言~

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值