https://leetcode.com/contest/6/problems/sum-of-left-leaves/
分析:求左叶子节点的和,就是先是叶子节点,然后是左儿子,叶子节点很容易判断,左儿子需要加一个标记。
1 class Solution { 2 public: 3 void dfs(TreeNode*root, bool f, int &s) { 4 if(!root) return; 5 if(!root->left && !root->right) { 6 if(f) s += root->val; 7 return; 8 } 9 if(root->left) { 10 dfs(root->left, 1, s); 11 } 12 if(root->right) { 13 dfs(root->right, 0, s); 14 } 15 16 } 17 int sumOfLeftLeaves(TreeNode* root) { 18 int res = 0; 19 dfs(root, 0, res); 20 return res; 21 } 22 };