Easy to understand Java Recursion solution


  • 0
    R
    public class Solution {
        public String tree2str(TreeNode t) {
                if(t==null)
                    return "";
                if(t.left==null && t.right==null)
                    return String.valueOf(t.val);
                    
                String toret=String.valueOf(t.val);
                String left="",right="";
                if(t.left!=null)
                    left=tree2str(t.left);            
                if(t.right!=null)
                    right= "("+tree2str(t.right)+")";
                return toret+"("+left+")"+right;
                
            }
        }
    
    
    

Log in to reply
 

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