LeetCode Construct String from Binary Tree

LeetCode 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. 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 relationship between the input and the output.

本题要求把一棵二叉树转换为一个字符串,使用先序遍历的方法,并且左右子树需要用括号括起来,但是要保证从该字符串能唯一恢复回原来的二叉树,而且要去掉不必要的空括号。 首先明确先序遍历:根左右,不难。然后要删掉不必要的空括号,观察第二个样例,发现如果左孩子为空,则左孩子的空括号不能省,但是如果右孩子或者左右孩子都为空,则他们的空括号可以省略。所以分几种情况递归求解即可。 代码如下: [cpp] class Solution { public: string tree2str(TreeNode* t) { if (!t)return ""; if (!t->left && !t->right)return to_string(t->val); if (!t->left)return to_string(t->val) + "()(" + tree2str(t->right) + ")"; if (!t->right)return to_string(t->val) + "(" + tree2str(t->left) + ")"; return to_string(t->val) + "(" + tree2str(t->left) + ")(" + tree2str(t->right) + ")"; } }; [/cpp] 本代码提交AC,用时19MS。]]>

Leave a Reply

Your email address will not be published. Required fields are marked *