mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 404. Sum of Left Leaves.md
This commit is contained in:
parent
9a8129a117
commit
e6bdd500df
49
404. Sum of Left Leaves.md
Normal file
49
404. Sum of Left Leaves.md
Normal file
@ -0,0 +1,49 @@
|
||||
# [404. Sum of Left Leaves](https://leetcode.com/problems/sum-of-left-leaves/description/)
|
||||
# 思路
|
||||
计算一棵二叉树所有左叶子的值之和。
|
||||
## 思路一
|
||||
设置一个初始为0的全局变量res,遍历一遍树,判断某节点的左子树是否是叶子,若是,则将这个叶子的值加至res,遍历完后返回res即可。
|
||||
|
||||
## 思路二
|
||||
直接递归计算结果res。因为某棵树的res等于其左子树的res加上右子树的res。
|
||||
|
||||
# C++
|
||||
## 思路一
|
||||
``` C++
|
||||
class Solution {
|
||||
private:
|
||||
int res = 0;
|
||||
bool is_leaf(TreeNode *p){ // 判断是否是叶子
|
||||
if(p == NULL) return false;
|
||||
return (p -> left == NULL && p -> right == NULL);
|
||||
}
|
||||
void find_left_leaf(TreeNode *root){
|
||||
if(root == NULL || is_leaf(root)) return;
|
||||
|
||||
if(is_leaf(root -> left)) res += root -> left -> val; // 左子树是叶子,加至res
|
||||
else find_left_leaf(root -> left);
|
||||
find_left_leaf(root -> right);
|
||||
}
|
||||
public:
|
||||
int sumOfLeftLeaves(TreeNode* root) {
|
||||
find_left_leaf(root);
|
||||
return res;
|
||||
}
|
||||
};
|
||||
```
|
||||
## 思路二
|
||||
``` C++
|
||||
class Solution {
|
||||
private:
|
||||
bool is_leaf(TreeNode *p){ // 判断是否是叶子
|
||||
if(p == NULL) return false;
|
||||
return (p -> left == NULL && p -> right == NULL);
|
||||
}
|
||||
public:
|
||||
int sumOfLeftLeaves(TreeNode* root) {
|
||||
if(root == NULL || is_leaf(root)) return 0;
|
||||
if(is_leaf(root -> left)) return (root -> left -> val) + sumOfLeftLeaves(root -> right);
|
||||
else return sumOfLeftLeaves(root -> left) + sumOfLeftLeaves(root -> right);
|
||||
}
|
||||
};
|
||||
```
|
||||
Loading…
Reference in New Issue
Block a user