Sponsored
Sponsored
This approach uses Depth-First Search (DFS) to explore all paths from the root to the leaf nodes. Starting from the root, we recursively visit each node, accumulating the current path. When a leaf node is reached, we add the accumulated path to a list of paths. This can be implemented recursively and is optimal given the constraints.
Time Complexity: O(n), where n is the number of nodes in the tree, as we visit each node once.
Space Complexity: O(n), for the space used to store the recursion stack and the result paths.
1using System;
2using System.Collections.Generic;
3
4public class TreeNode {
5 public int val;
6 public TreeNode left;
7 public TreeNode right;
8 public TreeNode(int x) { val = x; }
9}
10
11public class Solution {
12 public IList<string> BinaryTreePaths(TreeNode root) {
13 List<string> paths = new List<string>();
14 if (root != null) Dfs(root, "", paths);
15 return paths;
16 }
17
18 private void Dfs(TreeNode node, string path, List<string> paths) {
19 if (node != null) {
20 path += node.val;
21 if (node.left == null && node.right == null) { // Leaf node
22 paths.Add(path);
23 } else {
24 path += "->";
25 Dfs(node.left, path, paths);
26 Dfs(node.right, path, paths);
27 }
28 }
29 }
30}
This C# approach utilizes a recursive method for generating paths similar to other languages. Each path is built from the root to the leaves, utilizing a recursive call stack to track the depth and path.
This approach utilizes an iterative Depth-First Search (DFS) with a stack. By storing the nodes and their paths on the stack, we can simulate the recursive DFS stack. This allows for constructing the paths through iterative backtracking.
Time Complexity: O(n), traversing each node once.
Space Complexity: O(n), as we maintain a stack proportional to the tree height.
1using System.Collections.Generic;
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> paths = new List<string>();
if (root == null) return paths;
Stack<(TreeNode, string)> stack = new Stack<(TreeNode, string)>();
stack.Push((root, root.val.ToString()));
while (stack.Count > 0) {
var (node, path) = stack.Pop();
if (node.left == null && node.right == null) {
paths.Add(path);
}
if (node.right != null) {
stack.Push((node.right, path + "->" + node.right.val));
}
if (node.left != null) {
stack.Push((node.left, path + "->" + node.left.val));
}
}
return paths;
}
}
This C# solution uses a stack to iteratively explore the tree, simulating recursive behavior through stack operations. The process accumulates paths, finalizing them once a leaf node is identified.