题目来源:https://leetcode.cn/problems/sum-of-left-leaves/description/
C++题解1:递归法,前序遍历。
1. 确定输入参数:当前节点,左叶子的和;
2. 确定终止条件:空节点时返回;
3. 确定单层递归逻辑:当该节点有左子树,判断是否为叶子节点,是则把它加入sum中,不是则进行下一步递归;当该节点有右子树,则进行下一步递归。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void getleft(TreeNode* node, int& sum) {
if(node == nullptr) return;
if(node->left) {
if(node->left->left == nullptr && node->left->right == nullptr) {
sum = sum + node->left->val;
}
else getleft(node->left, sum);
}
if(node->right) getleft(node->right, sum);
return;
}
int sumOfLeftLeaves(TreeNode* root) {
int sum = 0;
if(root == nullptr) return 0;
getleft(root, sum);
return sum;
}
};
C++题解2:迭代法,层序遍历
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
stack<TreeNode*> st;
if (root == NULL) return 0;
st.push(root);
int result = 0;
while (!st.empty()) {
TreeNode* node = st.top();
st.pop();
if (node->left != NULL && node->left->left == NULL && node->left->right == NULL) {
result += node->left->val;
}
if (node->right) st.push(node->right);
if (node->left) st.push(node->left);
}
return result;
}
};