My C# solution Beat 73%


  • 0
    T
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left;
     *     public TreeNode right;
     *     public TreeNode(int x) { val = x; }
     * }
     */
    using System.Text;
    
    public class Solution {
        void Helper(TreeNode root, string path, IList<string> list, bool isRoot)
        {
            if(isRoot)
                path += root.val;
            else
                path += "->" + root.val;
            
            if(root.left != null)
            {
                Helper(root.left, path, list, false);
            }
            
            if(root.right != null)
            {
                Helper(root.right, path, list, false);
            }
            
            if(root.left == null && root.right == null)
            {
                list.Add(path);
            }
        }
        
        public IList<string> BinaryTreePaths(TreeNode root) 
        {
            List<string> list = new List<string>();
            if(root != null)
                Helper(root, "", list, true);
            return list as IList<string>;
        }
    }
    

Log in to reply
 

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