
Sponsored
Sponsored
This approach involves using recursive DFS to traverse the tree. At each node, determine if it is a left leaf. If it is, add its value to the sum and recursively continue to search for more left leaves in the subtree.
The time complexity is O(n) where n is the number of nodes, as we visit each node once. The space complexity is O(h), where h is the height of the tree, due to the recursive call stack.
1public class TreeNode {
2 public int val;
3 public TreeNode left;
4 public TreeNode right;
5 public TreeNode(int x) { val = x; }
6}
7
8public class Solution {
9 public int Dfs(TreeNode node, bool isLeft) {
10 if (node == null) return 0;
11 if (node.left == null && node.right == null && isLeft) return node.val;
12 return Dfs(node.left, true) + Dfs(node.right, false);
13 }
14 public int SumOfLeftLeaves(TreeNode root) {
15 return Dfs(root, false);
16 }
17}In C#, the recursive DFS is implemented in a similar manner. A helper method Dfs is crafted to traverse the binary tree and sum up the values of all left leaves.
This approach applies iterative DFS using a stack. By exploring each node iteratively, it checks if a node qualifies as a left leaf and accumulates its value to the sum. It manages to mimic a recursive pattern iteratively.
The time complexity is O(n) for navigating each tree node once. Space complexity is O(n) due to maintaining a stack proportional to the number of nodes.
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 int SumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
int sum = 0;
Stack<(TreeNode node, bool isLeft)> stack = new Stack<(TreeNode, bool)>();
stack.Push((root, false));
while (stack.Count > 0) {
var (node, isLeft) = stack.Pop();
if (node.left == null && node.right == null && isLeft) {
sum += node.val;
}
if (node.right != null) {
stack.Push((node.right, false));
}
if (node.left != null) {
stack.Push((node.left, true));
}
}
return sum;
}
}C# utilizes tuple usage within stack operations to manage the node traversal iteratively. Efforts revolve around ensuring all node visitation and left leaf value accumulation are vigilantly observed.