C# Solutions (Beats 85%)


  • 1
    K
     * Definition for a binary tree node.
     * public class TreeNode {
     *     public int val;
     *     public TreeNode left;
     *     public TreeNode right;
     *     public TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public IList<string> BinaryTreePaths(TreeNode root)
        {
            List<string> list = new List<string>();
            Helper(list, root, new StringBuilder());
            return list;
        }
        
        private void Helper(List<string> list, TreeNode node, StringBuilder sb){
            if (node == null)
                return;
            
            sb.Append(node.val);
            
            if (node.left == null && node.right == null){
                list.Add(sb.ToString());
            }
            
            if (node.left != null)
            {
                sb.Append("->");
                Helper(list, node.left, sb);
                sb.Length -= node.left.val.ToString().Length + 2;
            }
            
            if (node.right != null)
            {
                sb.Append("->");
                Helper(list, node.right, sb);
                sb.Length -= node.right.val.ToString().Length + 2;
            }
        }
    }

Log in to reply
 

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