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