Binary Tree Return All Root-To-Leaf Paths

Given the root of a binary tree, return all root-to-leaf paths in any order.

A leaf is a node with no children.

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left;
 *     public TreeNode right;
 *     public TreeNode(int val=0, TreeNode left=null, TreeNode right=null) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
public class Solution {
    
   public IList<string> BinaryTreePaths(TreeNode root)
    {
        IList<string> result = new List<string>();
        StringBuilder sb = new StringBuilder();
        DFS(root, result, sb);
        return result;

    }
    public void DFS(TreeNode root, IList<string> result, StringBuilder sb)
    {
       if (root == null)
            return;

        int length = sb.Length;
        sb.Append(root.val);
        if (root.left == null && root.right == null)
        {
            result.Add(sb.ToString());
            
        }
        else
        {
            sb.Append("->");
            DFS(root.left, result, sb);
            DFS(root.right, result, sb);

        }
        sb.Length = length;

    }
}

Last updated