404. 左叶子之和
题目
传送门:https://leetcode.cn/problems/sum-of-left-leaves/
算法设计:深度优先搜索
遍历一遍二叉树,找到左叶子节点,累加值。
问题在于,左叶子怎么表示?
if (root.left != null && root.left.left == null && root.left.right == null)
// 找到左侧的叶子节点,记录累加值
sum += root.left.val;
我们有更好的写法:
- 在判断叶子节点的时候,把右叶子节点设置为 0
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root, bool isleft = false) {
if (!root) return 0;
if (!root->left && !root->right) return isleft ? root->val : 0;
// 是叶子节点,且是左叶子节点
return sumOfLeftLeaves(root->left, true) + sumOfLeftLeaves(root->right, false);
// 左叶子累加和 = 左叶子和 + 0
}
};