404、左子叶之和
一、递归法
1、递归思路
递归三要素:
- 递归返回值和参数:返回值为当前节点为根节点的子树的左子叶之和,参数为当前节点
- 单层递归逻辑:
如果当前根节点具有一个左子叶,则当前节点左子叶之和 = 左子叶的值 + 右子树的左子叶之和
如果当前根节点不具有左子叶,则当前节点左子叶之和 = 左子树的左子叶之和 + 右子树的左子叶之和 - 递归终止条件:如果当前节点为空,则返回0
2、递归代码
class Solution {
public:
//递归函数返回值和参数
int sumOfLeftLeaves(TreeNode* root) {
//递归终止条件
if (root == nullptr) return 0;
//单层递归逻辑
int leftValue = sumOfLeftLeaves(root->left); // 左子树左子叶之和
int rightValue = sumOfLeftLeaves(root->right); // 右子树左子叶之和
//如果当前节点具有左子叶,则当前节点左子叶之和 = 左子叶的值 + 右子树的左子叶之和
if(root->left && !root->left->left && !root->left->right) return root->left->val + rightValue;
//如果当前节点不具有左子叶,则当前节点左子叶之和 = 左子树的左子叶之和 + 右子树的左子叶之和
return leftValue + rightValue;
}
};
二、迭代法
1、迭代法思路
迭代法就是遍历二叉树,找出左子叶,然后累加求和即可,使用层次遍历,深度遍历均可
2、迭代法代码
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
int res = 0;
queue<TreeNode*> que;
if(root == nullptr) return res;
que.push(root);
while(!que.empty()){
TreeNode* node = que.front();
que.pop();
if(node->left){
//在处理左孩子的时候,判断是否为左子叶,如果是就累加求和;如果不是就插入队列继续遍历
if(node->left->left == nullptr && node->left->right == nullptr){
res += node->left->val;
} else {
que.push(node->left);
}
}
if(node->right) que.push(node->right);
}
return res;
}
};