赞
踩



我们以一个二叉树为例

左叶子的特点是什么?
所以我们用leftnode保存root->lefe节点,判断条件为leftnode存在,并且不存在leftnode->left和leftnode->right,如果满足条件,则将val加到全局变量x中去,x的初始值为0,然后递归root->right
如果不满足条件,就继续递归root->left和root->right
- /**
- * struct TreeNode {
- * int val;
- * struct TreeNode *left;
- * struct TreeNode *right;
- * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
- * };
- */
- class Solution {
- public:
- /**
- * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
- *
- *
- * @param root TreeNode类
- * @return int整型
- */
- int count=0;
- int sumOfLeftLeaves(TreeNode* root) {
- if(root==nullptr)
- return 0;
- TreeNode* leftnode=root->left;
- if(leftnode&&!leftnode->left&&!leftnode->right)
- {
- count +=leftnode->val;
- sumOfLeftLeaves(root->right);
- }
- else {
- {
- sumOfLeftLeaves(root->left);
- sumOfLeftLeaves(root->right);
- }
- }
- return count;
- }
- };


Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。