[C++] [Java] 1 liner


  • 11

    C++ 1 liner

    class Solution {
    public:
        string tree2str(TreeNode* t) {
            return !t ? "" : to_string(t->val) + (t->left ? "(" + tree2str(t->left) + ")" : t->right ? "()" : "")
                                               + (t->right ? "(" + tree2str(t->right) + ")" : "");
        }
    };
    

    Java 1 liner

    class Solution {
        public String tree2str(TreeNode t) {
            return t == null ? "" : t.val + (t.left != null ? "(" + tree2str(t.left) + ")" : t.right != null ? "()" : "")
                                          + (t.right != null ? "(" + tree2str(t.right) + ")" : "");
        }
    }
    

    C++ Cozy

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

    Java Cozy

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

Log in to reply
 

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