Construct String from Binary Tree

Problem

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.

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */

Recursion solution using preorder traversal

public class Solution {
    public String tree2str(TreeNode t) {
        if (t == null) return "";
        String result = t.val + "";
        String left = tree2str(t.left);
        String right = tree2str(t.right);
        if (left.equals("") && right.equals("")) return result;
        if (left.equals("")) return result + "()(" + right + ")";
        if (right.equals("")) return result + "(" + left + ")";
        return result + "(" + left + ")" + "(" + right + ")";
    }
}

Optimized Space using StringBuilder

public class Solution {
    public String tree2str(TreeNode t) {
        StringBuilder sb = new StringBuilder();
        helper(t, sb);
        return sb.toString();
    }

    private void helper(TreeNode t, StringBuilder sb) {
        if (t != null) {
            sb.append(t.val);
            if (t.left != null || t.right != null) {
                sb.append("(");
                helper(t.left, sb);
                sb.append(")");
                if (t.right != null) {
                    sb.append("(");
                    helper(t.right, sb);
                    sb.append(")");
                }
            }
        }
    }
}

Analysis

This is a typical preorder traversal problem
In the first solution, we traversal the given TreeNode, then it's left and it's right
Then according to the result of traversal left and right we return the required string

In the second solution we use StringBuilder to save space
We add the current TreeNode val as long as it is not null
Then we check whether it's left or right is null
Notice that we must use || for t.right because we need to append the empty parenthesis () if the left is null

Complexity Analysis

  • Time: O(n), where n is the number of nodes in the tree. In preorder traversal we visited all nodes of the given tree.
  • Space: O(n), the depth of tree can be equal to number of nodes if it's skewed tree.

results matching ""

    No results matching ""