题目链接https://leetcode-cn.com/problems/construct-string-from-binary-tree
你需要采用前序遍历的方式,将一个二叉树转换成一个由括号和整数组成的字符串。
空节点则用一对空括号 “()” 表示。而且你需要省略所有不影响字符串与原始二叉树之间的一对一映射关系的空括号对。
思路:相当于前序遍历的升级,搞得花里胡哨的
/**
* 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) return "";//如果为空,返回空字符串
if(!t->left && !t->right) return to_string(t->val);//如果为叶子结点,将当前节点转换成字符串
if(!t->right) //如果右子树为空,由上面的if判断条件可知左孩子不为空,后面不需要添加括号,直接返回 当前节点(左子树的字符串)
return to_string(t->val)+"("+ tree2str(t->left)+ ")";
//正常情况下,返回 当前节点(左子树字符串 右孩子字符串)
return to_string(t->val)+"("+ tree2str(t->left) +")"+"("+tree2str(t->right)+")";
}
};