Possible recursive C# Solution


  • 0

    A simple recursive function using an additional list to store the leaf parent tree:

    public IList<string> BinaryTreePaths(TreeNode root)
    {
        var result = new List<string>();
        var parentPath = new List<TreeNode>();
    
        BinaryTreePathsRec(root, parentPath, result);
    
        return result;
    }
    
    private void BinaryTreePathsRec(TreeNode node, List<TreeNode> parentPath, List<string> result)
    {
        if (node == null)
            return;
    
        if (node.left == null && node.right == null)
            result.Add(GetStringPath(node, parentPath));
        else
            parentPath.Add(node);
    
        if (node.left != null)
            BinaryTreePathsRec(node.left, parentPath, result);
    
        if (node.right != null)
            BinaryTreePathsRec(node.right, parentPath, result);
    
        if (parentPath.Contains(node))
            parentPath.Remove(node);
    }
    
    private string GetStringPath(TreeNode node, List<TreeNode> parentPath)
    {
        var sb = new StringBuilder();
        for(int i = 0; i < parentPath.Count; i++)
        {
            sb.Append($"{parentPath[i].val} -> ");
        }
        sb.Append(node.val);
    
        return sb.ToString();
    }
    

Log in to reply
 

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