Find the sum of all left leaves in a given binary tree.
Example:
3 / \ 9 20 / \ 15 7There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
private int sum; public int SumOfLeftLeaves(TreeNode root) { Chuck(root, false); return sum; } private void Chuck(TreeNode node, bool isLeft) { if (node == null) { return; } if (node.left == null && node.right == null)//leaf node { if (isLeft) { sum = sum + node.val; } } else { Chuck(node.left, true); Chuck(node.right, false); } }
Runtime: 92 ms, faster than 98.11% of C# online submissions for Sum of Left Leaves.
Memory Usage: 22.7 MB, less than 5.16% of C# online submissions forSum of Left Leaves.