Merge pull request #71 from Chengkq/master

添加0404.左叶子之和 Java版本
This commit is contained in:
Carl Sun
2021-05-13 17:44:06 +08:00
committed by GitHub
3 changed files with 46 additions and 5 deletions

View File

@ -253,7 +253,6 @@ public:
## 其他语言版本 ## 其他语言版本
Java Java

View File

@ -353,7 +353,6 @@ public:
## 其他语言版本 ## 其他语言版本
Java Java

View File

@ -159,9 +159,51 @@ public:
## 其他语言版本 ## 其他语言版本
Java Java
**递归**
```java
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
int leftValue = sumOfLeftLeaves(root.left); // 左
int rightValue = sumOfLeftLeaves(root.right); // 右
int midValue = 0;
if (root.left != null && root.left.left == null && root.left.right == null) { // 中
midValue = root.left.val;
}
int sum = midValue + leftValue + rightValue;
return sum;
}
}
```
**迭代**
```java
class Solution {
public int sumOfLeftLeaves(TreeNode root) {
if (root == null) return 0;
Stack<TreeNode> stack = new Stack<> ();
stack.add(root);
int result = 0;
while (!stack.isEmpty()) {
TreeNode node = stack.pop();
if (node.left != null && node.left.left == null && node.left.right == null) {
result += node.left.val;
}
if (node.right != null) stack.add(node.right);
if (node.left != null) stack.add(node.left);
}
return result;
}
}
```
Python Python
@ -176,3 +218,4 @@ Go
* B站视频[代码随想录](https://space.bilibili.com/525438321) * B站视频[代码随想录](https://space.bilibili.com/525438321)
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ) * 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div> <div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>