leetcode 606. Construct String from Binary Tree 前序遍历 + 深度优先遍历DFS

水深无声 2022-06-02 21:13 258阅读 0赞

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.

本题题意很简单,就是遍历二叉树来添加括号,直接前序遍历即可

代码如下:

  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <set>
  5. #include <queue>
  6. #include <stack>
  7. #include <string>
  8. #include <climits>
  9. #include <algorithm>
  10. #include <sstream>
  11. #include <functional>
  12. #include <bitset>
  13. #include <numeric>
  14. #include <cmath>
  15. #include <regex>
  16. using namespace std;
  17. /*
  18. struct TreeNode
  19. {
  20. int val;
  21. TreeNode *left;
  22. TreeNode *right;
  23. TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  24. };
  25. */
  26. class Solution
  27. {
  28. public:
  29. string tree2str(TreeNode* t)
  30. {
  31. if (t == NULL)
  32. return "";
  33. else
  34. {
  35. string res = to_string(t->val);
  36. string left = tree2str(t->left), right = tree2str(t->right);
  37. if (left == "" && right == "")
  38. return res;
  39. if (left == "")
  40. return res + "()" + "(" + right + ")";
  41. if (right == "")
  42. return res + "(" + left + ")";
  43. return res + "(" + left + ")" + "(" + right + ")";
  44. }
  45. }
  46. };

发表评论

表情:
评论列表 (有 0 条评论,258人围观)

还没有评论,来说两句吧...

相关阅读