[leetcode]: 606. Construct String from Binary Tree

来源:互联网 发布:程序员怎么选择公司 编辑:程序博客网 时间:2024/05/21 10:13

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)”
原始结果 “1(2(4)())(3()())”, 去掉不必要的空括号,结果为”1(2(4))(3)”.

Example 2:
Input: Binary tree: [1,2,3,null,4]

   1 /   \2     3 \    4 

Output: “1(2()(4))(3)”
这里不需要去掉空括号,否则这个字符串对应的二叉树不唯一。

总结规律:
当左节点为空,右节点不为空,左节点的空括号保留。
当左节点不为空,右节点为空,右节点的空括号可以去掉
当左右节点均为空,两个空括号都要去掉。

2.分析

前序遍历,递归实现

3.代码

class Solution {public:    string tree2str(TreeNode* t) {              if (t == NULL)            return "";        string res = to_string(t->val);        if (t->left&&t->right)            return res + "(" + tree2str(t->left) + ")" + "(" + tree2str(t->right) + ")";        else if (t->left)            return res + "(" + tree2str(t->left) + ")";        else if (t->right)            return res + "()(" + tree2str(t->right) + ")";        else            return res;    }};
原创粉丝点击