606. Construct String from Binary Tree

1.问题描述

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.
Example 1:
Input: Binary tree: [1,2,3,4]
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: 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 relat

来自 https://leetcode.com/problems/construct-string-from-binary-tree/description/

2.题目分析

用前序遍历遍历二叉树,构造出一个由括号和整数组成的字符串,空节点需要用空括号对“()”表示。而且需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。左右子节点用括号括起来,当只有左子节点则只对左子节点经行括号,右子节点忽略;当只有右子节点是,左子节点用“()”表示。由于二叉树的节点的值是int,需要转成string,用到c++11的新特性,string s= tostring(int a);
难点在于二叉树的前序遍历的递归调用方法,递归调用的入栈出栈,反复调用比较难理解。

3.C++代码

//我的代码:(beats 95%)
void PreOrder(TreeNode *p, string &s)
{
    if (p != NULL)
    {
        if (p->left&&p->right)
        {
            s += to_string(p->val);
            s += "(";
            PreOrder(p->left, s);
            s += ")";
            s += "(";
            PreOrder(p->right, s);
            s += ")";
        }
        else if (p->left == NULL&&p->right)
        {
            s += to_string(p->val);
            s += "(";
            //s += "NULL";
            s += ")";
            s += "(";
            PreOrder(p->right, s);
            s += ")";
        }
        else if (p->left &&p->right == NULL)
        {
            s += to_string(p->val);
            s += "(";
            PreOrder(p->left, s);
            s += ")";
            //s += "(";
            //s += "NULL";
            //s += ")";
        }
        else
        {
            s += to_string(p->val);
        }

    }
}
string tree2str(TreeNode* t)
{
    string s = "";
    PreOrder(t, s);
    return s;
}

4.int和string相互转换

参考:
https://blog.csdn.net/u010510020/article/details/73799996

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值