Small recursive function - hacked


  • 0
    A

    Funnily this small recursive function solves the problem as well. :)

    public class Solution {
      public string Tree2str(TreeNode root) {
        if (root==null)
          return "";
        string res = (root.val + "(" + Tree2str(root.left) + ")" +  "(" +
          Tree2str(root.right) + ")").Replace("())",")").Replace(")()",")").
          Replace("()()","");
        if (res.EndsWith("()"))
          return res.Substring(0, res.Length-2);
        return res;
      }
    }
    

Log in to reply
 

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