Simple JavaScript solution


  • 0

    There are 4 cases to check:

    1. the current node is null, return empty string
    2. both left and right nodes are null, return the root value, e.g. "1"
    3. only the right node is null, return root value and left value, e.g. "1(2)"
    4. both left and right nodes are not null, return both left and right values, e.g. "1(2)(3)"
    /**
     * @param {TreeNode} t
     * @return {string}
     */
    const tree2str = root => {
        if (!root) {
            return ''; // sanity check
        }
        
        const val = root.val;
        const left = tree2str(root.left);
        const right = tree2str(root.right);
        
        if (!left && !right) {
            return `${val}`; // both left and right are empty
        }
        
        if (!right) {
            return `${val}(${left})`; // right is empty, keep the left
        }
        
        return `${val}(${left})(${right})`; // left and right are not empty
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.