My Java recursion solution


  • 0
    L
    public class Solution {
        
       StringBuilder sb = new StringBuilder();
       public String tree2str(TreeNode t) {
           treeTra(t);
           return sb.toString();
        }
    
        public void treeTra(TreeNode t) {
            if (t == null) {
                return;
            }
            sb.append(t.val);
            if (t.left != null || t.right != null) {
                sb.append("(");
            }
            tree2str(t.left);
            if (t.left != null || t.right != null) {
                sb.append(")");
            }
            if (t.right != null) {
                sb.append("(");
            }
            tree2str(t.right);
            if (t.right != null) {
                sb.append(")");
            }
        }
    }
    

Log in to reply
 

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