/** * 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 = 0; foreach (var l in list) { sum += l.val; } return sum; } }
https://leetcode.com/problems/sum-of-left-leaves/#/description
补充一个python的实现:
1 class Solution: 2 def __init__(self): 3 self.leftsum = 0 4 def preOrder(self,root): 5 if root != None: 6 if root.left != None and root.left.left == None and root.left.right == None: 7 self.leftsum += root.left.val 8 self.preOrder(root.left) 9 self.preOrder(root.right) 10 11 def sumOfLeftLeaves(self, root: TreeNode) -> int: 12 self.preOrder(root) 13 return self.leftsum