/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
List<TreeNode> list1 = new List<TreeNode>();
List<TreeNode> list2 = new List<TreeNode>();
private void postTree(TreeNode root)
{
if (root != null)
{
if (root.left != null)
{
list1.Add(root.left);
postTree(root.left);
} if (root.right != null)
{
postTree(root.right);
}
//左叶子,是左子树并且是叶子 if (root.left == null && root.right == null)//叶子节点
{
//如何判断是左子树呢
list2.Add(root);
}
}
} public int SumOfLeftLeaves(TreeNode root)
{
postTree(root); var list = list1.Intersect(list2); var sum = ; foreach (var l in list)
{
sum += l.val;
} return sum;
}
}
https://leetcode.com/problems/sum-of-left-leaves/#/description
补充一个python的实现:
class Solution:
def __init__(self):
self.leftsum =
def preOrder(self,root):
if root != None:
if root.left != None and root.left.left == None and root.left.right == None:
self.leftsum += root.left.val
self.preOrder(root.left)
self.preOrder(root.right) def sumOfLeftLeaves(self, root: TreeNode) -> int:
self.preOrder(root)
return self.leftsum