Java beats 99.74% runtime. Simple Solution


  • 0
    M

    https://leetcode.com/submissions/detail/108478395/
    0_1499282995889_8bc09658-e62b-4db1-a5f2-9a132fb88fe1-image.png

    public class Solution {
        public String tree2str(TreeNode t) {
            if(t == null){return "";}
            
            StringBuilder sb = new StringBuilder();
            preOrder(t,sb);
            return sb.toString();
        }
        
        private void preOrder(TreeNode t, StringBuilder sb){
            sb.append(t.val);
            if(t.left != null){
                sb.append("(");
                preOrder(t.left, sb);
                sb.append(")");
            }else if(t.left == null && t.right != null){
                sb.append("()");
            }
            
            if(t.right != null){
                sb.append("(");
                preOrder(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.