C# solution


  • 1
    S
    public class Solution {
        public IList<string> BinaryTreePaths(TreeNode root) 
        {
            var result = new List<string>();
            Helper(result, root, new StringBuilder());
            return result;
        }
        
        private void Helper(List<string> result, TreeNode root, StringBuilder sb)
        {
            if(root == null)
                return;
            var len = sb.Length;
            sb.Append(root.val);
            if(root.left == null && root.right == null)
            {
                result.Add(sb.ToString());
            }
            else
            {
                sb.Append("->");
                Helper(result, root.left, sb);
                Helper(result, root.right, sb);
            }
            sb.Length = len;
        }
    }
    

  • 0

    Good dfs soltion. Is it O(N) time since it scans all nodes of the tree (p.s. would be helpful if comment the usage of len&sb.Length trick.


Log in to reply
 

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