给定二叉树的根节点
root
,返回所有左叶子之和。示例 1:
输入: root = [3,9,20,null,null,15,7] 输出: 24 解释: 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24示例 2:
输入: root = [1] 输出: 0提示:
- 节点数在
[1, 1000]
范围内-1000 <= Node.val <= 1000
递归
class Solution {
public:int sumOfLeftLeaves(TreeNode* root) {if(root==nullptr)return 0;int leftval=sumOfLeftLeaves(root->left);int rightval=sumOfLeftLeaves(root->right);if(root->left!=nullptr&&root->left->left==nullptr&&root->left->right==nullptr)leftval=root->left->val;int sum=leftval+rightval;return sum;}
};
迭代:
class Solution {
public:int sumOfLeftLeaves(TreeNode* root) {stack<TreeNode *> s;s.push(root);int res=0;while(!s.empty()){TreeNode *cur=s.top();s.pop();if(cur->left!=nullptr&&cur->left->left==nullptr&&cur->left->right==nullptr)res+=cur->left->val;if(cur->left)s.push(cur->left);if(cur->right)s.push(cur->right);}return res;}
};