题意描述:
给定二叉树的根节点 root
,返回所有左叶子之和。
首先要了解左叶子的意思 :节点A的左孩子不为空,且左孩子的左右孩子都为空(说明是叶子节点),那么A节点的左孩子为左叶子节点。
递归法:
C++代码如下:
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root == NULL){
return 0;
}
if(root->left == NULL && root->right == NULL){
return 0;
}
int leftValue = sumOfLeftLeaves(root->left);
if(root->left && !root->left->left && !root->left->right){
leftValue = root->left->val;
}
int rightValue = sumOfLeftLeaves(root->right);
int sum = leftValue + rightValue;
return sum;
}
};
迭代法:
C++代码如下:
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;
}
};