mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
@ -253,7 +253,6 @@ public:
|
||||
|
||||
## 其他语言版本
|
||||
|
||||
|
||||
Java:
|
||||
|
||||
|
||||
@ -284,4 +283,4 @@ const check = (leftPtr, rightPtr) => {
|
||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||
* 知识星球:[代码随想录](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>
|
@ -353,7 +353,6 @@ public:
|
||||
|
||||
## 其他语言版本
|
||||
|
||||
|
||||
Java:
|
||||
|
||||
|
||||
@ -402,4 +401,4 @@ func abs(a int)int{
|
||||
* 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)
|
||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||
* 知识星球:[代码随想录](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>
|
@ -159,9 +159,51 @@ public:
|
||||
|
||||
## 其他语言版本
|
||||
|
||||
|
||||
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:
|
||||
|
||||
@ -176,3 +218,4 @@ Go:
|
||||
* B站视频:[代码随想录](https://space.bilibili.com/525438321)
|
||||
* 知识星球:[代码随想录](https://mp.weixin.qq.com/s/QVF6upVMSbgvZy8lHZS3CQ)
|
||||
<div align="center"><img src=../pics/公众号.png width=450 alt=> </img></div>
|
||||
|
||||
|
Reference in New Issue
Block a user