[C++] [Java] 1 liner


  • 14

    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 "";
            String s = new String(t.val + "");
            if (t.left != null) s += "(" + tree2str(t.left) + ")";
            else if (t.right != null) s += "()";
            if (t.right != null) s += "(" + tree2str(t.right) + ")";
            return s;
        }
    }
    

    Java StringBuilder

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

Log in to reply
 

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