Leetcode404
1.问题描述
2.解决方案
解法一:递归父亲节点
思路:
思路很简单,就是遍历然后如果遇见符合条件的左叶子结点就收集
1.首先是左叶子结点这个怎么判断,我将一个父亲结点加入到了递归函数的参数中,所以就很好判断root是左儿子还是右儿子了
2.这两个判断条件或者是终止条件这是我一开始没有想到的,father= =nullpter了说明root就是根节点嘛,但是不加这个判断会段错误,root= =nullptr就不说了肯定直接return了
if(root== nullptr) return;
father!= nullptr
3.递归过程也是很简单,father赋为当前结点就可以了
recursion(root,root->left);
recursion(root,root->right);
代码:
class Solution {
public:
int sum=0;
void recursion(TreeNode* father,TreeNode* root){
if(root== nullptr) return;
if(root->left== nullptr&&root->right== nullptr&&father!= nullptr&&father->left==root){
sum+=root->val;
return;
}
recursion(root,root->left);
recursion(root,root->right);
}
int sumOfLeftLeaves(TreeNode* root) {
recursion(nullptr,root);
return sum;
}
};
解法二:递归
1.这个递归通过if(root->left!= nullptr&&root->left->left== nullptr&&root->left->right== nullptr)来判断左叶子节点的,其实也可以如果是就加上,相当于root如果有一个左叶子就加上
2.最后的结果==root左右子树的左叶子加上root的左叶子
class Solution{
public:
int sumOfLeftLeaves(TreeNode* root) {
if(root== nullptr) return 0;
int minValue=0;
if(root->left!= nullptr&&root->left->left== nullptr&&root->left->right== nullptr){
minValue+=root->left->val;
}
return minValue+ sumOfLeftLeaves(root->left)+ sumOfLeftLeaves(root->right);
}
};
解法三:迭代
利用统一迭代法模拟遍历过程,我还没看统一迭代法