LeetCode 606: Construct String from Binary Tree Solution

Master LeetCode problem 606 (Construct String from Binary Tree), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

606. Construct String from Binary Tree

Problem Explanation

Explanation

To solve this problem, we can perform a preorder traversal of the binary tree while constructing the string representation based on the guidelines provided. We will handle different cases for nodes with children and without children as specified in the problem description. The algorithm involves recursively traversing the tree and appending the node values to the string along with parentheses for children when necessary.

  • Time complexity: O(n) where n is the number of nodes in the binary tree.
  • Space complexity: O(n) for the recursive call stack.

Solution Code

class Solution {
    public String tree2str(TreeNode t) {
        if (t == null) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        sb.append(t.val);
        
        if (t.left != null || t.right != null) {
            sb.append("(").append(tree2str(t.left)).append(")");
            if (t.right != null) {
                sb.append("(").append(tree2str(t.right)).append(")");
            }
        }
        
        return sb.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 606 (Construct String from Binary Tree)?

This page provides optimized solutions for LeetCode problem 606 (Construct String from Binary Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 606 (Construct String from Binary Tree)?

The time complexity for LeetCode 606 (Construct String from Binary Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 606 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 606 in Java, C++, or Python.

Back to LeetCode Solutions