LeetCode:606. 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)"

方法1:利用递归的方式

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public String tree2str(TreeNode t) {
        if (t == null)
            return "";
        
        String left = tree2str(t.left);
        String right = tree2str(t.right);
        
        //trimming
        left = left.isEmpty()&&right.isEmpty()?"":"("+left+")";
        right = right.isEmpty()?"":"("+right+")";
        return t.val + left + right;
        
    }
}

时间复杂度:O(n)

空间复杂度:O(n)


方法二:利用stringBuffer进行保存字符串

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public String tree2str(TreeNode t) {
        StringBuilder sb = new StringBuilder();
        getString(t, sb);
        return sb.toString();
    }
    public void getString(TreeNode root, StringBuilder sb){
       if(root == null){
           return;
       }
        sb.append(Integer.toString(root.val));
        if(root.left != null){
            sb.append("(");
            helper(root.left, sb);
            sb.append(")");
        }
        if(root.right != null){
            if(root.left == null){
                sb.append("()");              
            }
            sb.append("(");
            helper(root.right, sb);
            sb.append(")");           
        }                
    }
}

时间复杂度:O(n)

空间复杂度:O(n)

猜你喜欢

转载自blog.csdn.net/zy345293721/article/details/84304381