606. Construct String from Binary Tree 构造二叉树字符串

  • Total Accepted: 2202
  • Total Submissions: 3988
  • Difficulty: Easy
  • Contributors:love_Fawn

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. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * public int val;
  5. * public TreeNode left;
  6. * public TreeNode right;
  7. * public TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public string Tree2str(TreeNode t) {
  12. if (t == null) return "";
  13. return DFS(t);
  14. }
  15. static public string DFS(TreeNode t) {
  16. StringBuilder builder = new StringBuilder();
  17. builder.Append(t.val);
  18. if (t.left != null) {
  19. builder.Append("(");
  20. builder.Append(DFS(t.left));
  21. builder.Append(")");
  22. }
  23. if (t.right != null) {
  24. if (t.left == null) {
  25. builder.Append("()");
  26. }
  27. builder.Append("(");
  28. builder.Append(DFS(t.right));
  29. builder.Append(")");
  30. }
  31. return builder.ToString();
  32. }
  33. }






原文地址:https://www.cnblogs.com/xiejunzhao/p/6b7c16e817570b39ca5ee485537cc8bc.html