26 ms C++ solution


  • 0
    B

    Code:

    class Solution {
    public:
        string tree2str(TreeNode* t) {
            if(!t)
                return "";
            str += std::to_string(t->val);
            if(t->left) {
                str += "(";
                tree2str(t->left);
                str += ")";   
            }
            
            if(!t->left && t->right)
                str += "()";
            
            if(t->right) {
                str += "(";
                tree2str(t->right);
                str += ")";   
            }
            
            return str;
        }
    private:
        std::string str = "";
    };
    

    Logic:

    • check if node exists

    • add value of node to result string

    • check if left child exists
      - YES : add "(" to result string and recursively call tree2str method with left child as parameter. And finally add ")" to complete the block in result string.
      - NO : check if right child of the tree exists and if it exists then add "()" to the result string.

    • check if right child exists
      - YES : add "(" to result string and recursively call tree2str method with left child as parameter. And finally add ")" to complete the block in result string.

    • return result string.

    Lemme know if you guys have a better way to do it :)


Log in to reply
 

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