mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 03:34:02 +08:00
@ -253,7 +253,6 @@ public:
|
|||||||
|
|
||||||
## 其他语言版本
|
## 其他语言版本
|
||||||
|
|
||||||
|
|
||||||
Java:
|
Java:
|
||||||
|
|
||||||
|
|
||||||
|
@ -353,7 +353,6 @@ public:
|
|||||||
|
|
||||||
## 其他语言版本
|
## 其他语言版本
|
||||||
|
|
||||||
|
|
||||||
Java:
|
Java:
|
||||||
|
|
||||||
|
|
||||||
|
@ -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>
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user